/* Copyright © 2020 Splunk Inc.
SPLUNK CONFIDENTIAL – Use or disclosure of this material in whole or
in part without a valid written license from Splunk Inc. is PROHIBITED. */
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// src/components/EventsViewer/index.tsx
var EventsViewer_exports = {};
__export(EventsViewer_exports, {
  default: () => EventsViewer_default
});
module.exports = __toCommonJS(EventsViewer_exports);

// esm-externals:lodash/assign
var assign_exports = {};
__export(assign_exports, {
  default: () => assign_default
});
var defaultImport = __toESM(require("lodash/assign"));
__reExport(assign_exports, require("lodash/assign"));
var assign_default = "default" in defaultImport ? defaultImport.default : defaultImport;

// esm-externals:react
var react_exports = {};
__export(react_exports, {
  default: () => react_default
});
var defaultImport2 = __toESM(require("react"));
__reExport(react_exports, require("react"));
var react_default = "default" in defaultImport2 ? defaultImport2.default : defaultImport2;

// esm-externals:lodash
var lodash_exports = {};
__export(lodash_exports, {
  default: () => lodash_default
});
var defaultImport3 = __toESM(require("lodash"));
__reExport(lodash_exports, require("lodash"));
var lodash_default = "default" in defaultImport3 ? defaultImport3.default : defaultImport3;

// esm-externals:@splunk/ui-utils/i18n
var i18n_exports = {};
__export(i18n_exports, {
  default: () => i18n_default
});
var defaultImport4 = __toESM(require("@splunk/ui-utils/i18n"));
__reExport(i18n_exports, require("@splunk/ui-utils/i18n"));
var i18n_default = "default" in defaultImport4 ? defaultImport4.default : defaultImport4;

// esm-externals:@splunk/react-ui/Menu
var Menu_exports = {};
__export(Menu_exports, {
  default: () => Menu_default
});
var defaultImport5 = __toESM(require("@splunk/react-ui/Menu"));
__reExport(Menu_exports, require("@splunk/react-ui/Menu"));
var Menu_default = "default" in defaultImport5 ? defaultImport5.default : defaultImport5;

// esm-externals:@splunk/react-ui/Button
var Button_exports = {};
__export(Button_exports, {
  default: () => Button_default
});
var defaultImport6 = __toESM(require("@splunk/react-ui/Button"));
__reExport(Button_exports, require("@splunk/react-ui/Button"));
var Button_default = "default" in defaultImport6 ? defaultImport6.default : defaultImport6;

// esm-externals:@splunk/react-ui/Dropdown
var Dropdown_exports = {};
__export(Dropdown_exports, {
  default: () => Dropdown_default
});
var defaultImport7 = __toESM(require("@splunk/react-ui/Dropdown"));
__reExport(Dropdown_exports, require("@splunk/react-ui/Dropdown"));
var Dropdown_default = "default" in defaultImport7 ? defaultImport7.default : defaultImport7;

// esm-externals:@splunk/react-ui/Paginator
var Paginator_exports = {};
__export(Paginator_exports, {
  default: () => Paginator_default
});
var defaultImport8 = __toESM(require("@splunk/react-ui/Paginator"));
__reExport(Paginator_exports, require("@splunk/react-ui/Paginator"));
var Paginator_default = "default" in defaultImport8 ? defaultImport8.default : defaultImport8;

// esm-externals:@splunk/ui-utils/format
var format_exports = {};
__export(format_exports, {
  default: () => format_default
});
var defaultImport9 = __toESM(require("@splunk/ui-utils/format"));
__reExport(format_exports, require("@splunk/ui-utils/format"));
var format_default = "default" in defaultImport9 ? defaultImport9.default : defaultImport9;

// src/components/ValueMenuItem/index.tsx
var ValueMenuItem = class extends react_default.PureComponent {
  constructor() {
    super(...arguments);
    /**
     * Handler for click events on this component. Call the onclick
     * prop with the DOM event triggering the click and the `value`
     * prop that was passed in by the parent component.
     * @param {MouseEvent} e DOM event
     */
    __publicField(this, "handleClick", (e) => {
      this.props.onClick(e, { value: this.props.value });
    });
  }
  render() {
    const _a = this.props, { value, onClick, children } = _a, otherProps = __objRest(_a, ["value", "onClick", "children"]);
    return /* @__PURE__ */ react_default.createElement(Menu_default.Item, __spreadValues({ key: value, onClick: this.handleClick }, otherProps), children);
  }
};

// src/styles.ts
var menu = {
  minWidth: "160px"
};

// src/components/PageLengthSelector/index.tsx
var perPageLabel = (pageLength) => (0, format_exports.sprintf)((0, i18n_exports._)("%(pageLength)d Per Page"), { pageLength });
var getPageLengthDropdownToggle = (pageLength) => /* @__PURE__ */ react_default.createElement(
  Button_default,
  {
    label: perPageLabel(pageLength),
    appearance: "subtle",
    isMenu: true,
    "data-test": "workflow-components:PageLengthSelector"
  }
);
var PageLengthSelector = ({ options = [10, 20, 50], pageLength, onChange }) => {
  return /* @__PURE__ */ react_default.createElement(Dropdown_default, { toggle: getPageLengthDropdownToggle(pageLength) }, /* @__PURE__ */ react_default.createElement(Menu_default, { style: menu, "data-test": "pagination-dropdown" }, [...options].sort((x, y) => x <= y ? -1 : 1).map((len) => /* @__PURE__ */ react_default.createElement(
    ValueMenuItem,
    {
      key: len,
      value: len,
      onClick: onChange,
      selected: len === pageLength,
      selectable: true
    },
    /* @__PURE__ */ react_default.createElement(react_default.Fragment, null, perPageLabel(len))
  ))));
};
var PageLengthSelector_default = PageLengthSelector;

// esm-externals:@splunk/react-ui/Table
var Table_exports = {};
__export(Table_exports, {
  default: () => Table_default
});
var defaultImport10 = __toESM(require("@splunk/react-ui/Table"));
__reExport(Table_exports, require("@splunk/react-ui/Table"));
var Table_default = "default" in defaultImport10 ? defaultImport10.default : defaultImport10;

// src/utils/actions.ts
var EVENT_ID_TUPLE = ["splunk_server", "index", "_cd"];
var INTERNAL_FIELDS_ARRAY = [
  "_bkt",
  "_cd",
  "_eventtype_color",
  "_fulllinecount",
  "_has_time",
  "_indextime",
  "_kv",
  "_mkv_child",
  "_raw",
  "_serial",
  "_si",
  "_sourcetype",
  "_span",
  "_subsecond"
];
var internalFields = new Set(INTERNAL_FIELDS_ARRAY);
var isInternalField = (field) => internalFields.has(field);
var isTimeField = (field) => field === "_time";
var testStringWithWildCardString = (wildCardString, stringToTest) => {
  const w = wildCardString.replace(/[.+^${}()|[\]\\]/g, "\\$&");
  const re = new RegExp(`^${w.replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
  return re.test(stringToTest);
};
var createWildcardRegex = (value) => {
  if (typeof value !== "string") {
    return false;
  }
  const wordBoundary = "\\b";
  const pattern = value === "*" ? ".*" : `${wordBoundary}${value.replace(/\*/g, ".*")}${wordBoundary}`;
  try {
    return new RegExp(pattern, "g");
  } catch (e) {
    return false;
  }
};
var isFuzzySubset = (subsetArray = [], supersetArray = []) => {
  const intersection = subsetArray.filter((subsetValue) => {
    const subsetValueRegex = createWildcardRegex(subsetValue.toString());
    return subsetValueRegex ? supersetArray.find(
      (supersetValue) => supersetValue && supersetValue.toString().match(subsetValueRegex) !== null
    ) : false;
  });
  return intersection.length === subsetArray.length;
};
var shouldShowActionAfterEventtypeFilter = (event, eventtypeValues = []) => {
  const eventtypeValuesCount = eventtypeValues.length;
  const isStarValue = eventtypeValuesCount === 1 && eventtypeValues[0] === "*";
  if (eventtypeValuesCount === 0 || isStarValue) {
    return true;
  }
  if ("eventtype" in event) {
    const eventtypeArray = Array.isArray(event.eventtype) ? event.eventtype : [event.eventtype];
    return isFuzzySubset(eventtypeValues, eventtypeArray);
  }
  return false;
};
var shouldShowEventActionAfterFieldFilter = (event, fieldFilters = []) => {
  const fieldFiltersCount = fieldFilters.length;
  const isStarValue = fieldFiltersCount === 1 && fieldFilters[0] === "*";
  if (fieldFiltersCount === 0 || isStarValue) {
    return true;
  }
  const fields = Object.keys(event);
  return isFuzzySubset(fieldFilters, fields);
};
var isWildcardMatch = (substring, superstring) => {
  const substringRegex = createWildcardRegex(substring);
  if (!substringRegex) {
    return false;
  }
  return substringRegex.exec(superstring) !== null;
};
var getFieldActionsMap = (event, renderFieldActions = {}, fields = []) => {
  const fieldActionsMap = {};
  Object.keys(renderFieldActions).forEach((fieldActionFieldRaw) => {
    fields.forEach((field) => {
      const currentActions = fieldActionsMap[field] || [];
      const fieldActionsByField = renderFieldActions[fieldActionFieldRaw];
      fieldActionsByField.forEach(({ eventtypeValues, fieldActionComponent }) => {
        if (isWildcardMatch(fieldActionFieldRaw, field) && shouldShowActionAfterEventtypeFilter(event, eventtypeValues)) {
          currentActions.push(fieldActionComponent);
          fieldActionsMap[field] = currentActions;
        }
      });
    });
  });
  return fieldActionsMap;
};
var getFilteredEventActionComponents = (event, renderEventActions = []) => {
  const renderEventActionComponents = [];
  renderEventActions.forEach((eventAction) => {
    const { eventtypeValues, fieldFilters, eventActionComponent } = eventAction;
    if (shouldShowActionAfterEventtypeFilter(event, eventtypeValues) && shouldShowEventActionAfterFieldFilter(event, fieldFilters)) {
      renderEventActionComponents.push(eventActionComponent);
    }
  });
  return renderEventActionComponents;
};
function generateKey(event, index, pageNumber) {
  let key = "";
  for (const field of EVENT_ID_TUPLE) {
    if (event[field]) {
      key = key === "" ? event[field].toString() : `${key}-${event[field]}`;
    }
  }
  return pageNumber ? `${key}-${index}-${pageNumber}` : `${key}-${index}`;
}
function rawString(event) {
  if (lodash_default.isObject(event)) {
    if (event._raw !== void 0) {
      if (lodash_default.isString(event._raw)) {
        return event._raw;
      }
      if (lodash_default.isObject(event._raw) && lodash_default.isString(event._raw.value)) {
        return event._raw.value;
      }
    }
  } else if (lodash_default.isString(event)) {
    return event;
  }
  return JSON.stringify(event);
}
function isJsonString(str) {
  if (!lodash_default.isString(str)) {
    return false;
  }
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

// esm-externals:styled-components
var styled_components_exports = {};
__export(styled_components_exports, {
  default: () => styled_components_default
});
var defaultImport11 = __toESM(require("styled-components"));
__reExport(styled_components_exports, require("styled-components"));
var styled_components_default = "default" in defaultImport11 ? defaultImport11.default : defaultImport11;

// esm-externals:@splunk/react-ui/JSONTree
var JSONTree_exports = {};
__export(JSONTree_exports, {
  default: () => JSONTree_default
});
var defaultImport12 = __toESM(require("@splunk/react-ui/JSONTree"));
__reExport(JSONTree_exports, require("@splunk/react-ui/JSONTree"));
var JSONTree_default = "default" in defaultImport12 ? defaultImport12.default : defaultImport12;

// esm-externals:@splunk/themes
var themes_exports = {};
__export(themes_exports, {
  default: () => themes_default
});
var defaultImport13 = __toESM(require("@splunk/themes"));
__reExport(themes_exports, require("@splunk/themes"));
var themes_default = "default" in defaultImport13 ? defaultImport13.default : defaultImport13;

// esm-externals:@splunk/visualization-context/FeatureFlagContext
var FeatureFlagContext_exports = {};
__export(FeatureFlagContext_exports, {
  default: () => FeatureFlagContext_default
});
var defaultImport14 = __toESM(require("@splunk/visualization-context/FeatureFlagContext"));
__reExport(FeatureFlagContext_exports, require("@splunk/visualization-context/FeatureFlagContext"));
var FeatureFlagContext_default = "default" in defaultImport14 ? defaultImport14.default : defaultImport14;

// esm-externals:lodash/has
var has_exports = {};
__export(has_exports, {
  default: () => has_default
});
var defaultImport15 = __toESM(require("lodash/has"));
__reExport(has_exports, require("lodash/has"));
var has_default = "default" in defaultImport15 ? defaultImport15.default : defaultImport15;

// esm-externals:@splunk/react-ui/Link
var Link_exports = {};
__export(Link_exports, {
  default: () => Link_default
});
var defaultImport16 = __toESM(require("@splunk/react-ui/Link"));
__reExport(Link_exports, require("@splunk/react-ui/Link"));
var Link_default = "default" in defaultImport16 ? defaultImport16.default : defaultImport16;

// esm-externals:@splunk/ui-utils/id
var id_exports = {};
__export(id_exports, {
  default: () => id_default
});
var defaultImport17 = __toESM(require("@splunk/ui-utils/id"));
__reExport(id_exports, require("@splunk/ui-utils/id"));
var id_default = "default" in defaultImport17 ? defaultImport17.default : defaultImport17;

// src/components/MaybeFieldLink/index.tsx
var FieldValueContainer = styled_components_default.div`
    display: inline;
    color: ${themes_exports.variables.contentColorActive};

    ${// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
({ $highlighted }) => $highlighted && styled_components_exports.css`
                background-color: ${(0, themes_exports.pick)({
  dark: themes_exports.variables.static17,
  light: themes_exports.variables.static4
})};
            `}
`;
var StyledLink = styled_components_default(Link_default)`
    color: inherit;
    text-decoration: underline;
`;
var maybeFieldLink = (field, value, onFieldClicked, onTimeClicked, isField, timeFieldAdditionalProps, fieldAdditionalProps) => {
  if (onTimeClicked && isTimeField(field)) {
    return /* @__PURE__ */ react_default.createElement(
      StyledLink,
      __spreadValues({
        role: "button",
        onClick: (e) => {
          e.preventDefault();
          onTimeClicked(e, { time: value });
        }
      }, timeFieldAdditionalProps),
      field
    );
  }
  if (onFieldClicked && !isTimeField(field) && (!isField || isField(field))) {
    return /* @__PURE__ */ react_default.createElement(
      StyledLink,
      __spreadValues({
        role: "button",
        onClick: (e) => {
          e.preventDefault();
          onFieldClicked(e, { field, value });
        }
      }, fieldAdditionalProps),
      field
    );
  }
  return /* @__PURE__ */ react_default.createElement("span", null, field);
};
var MaybeFieldValueLink = (props) => {
  const { field, value, onFieldValueClicked, isField, isHighlighted } = props;
  const ref = react_default.useRef(null);
  const isLink = onFieldValueClicked && !isTimeField(field) && (!isField || isField(field));
  react_default.useEffect(() => {
    if (!isLink) {
      return void 0;
    }
    const handleLinkClick = (e) => e.preventDefault();
    const element = ref.current;
    element.addEventListener("click", handleLinkClick);
    return () => {
      element.removeEventListener("click", handleLinkClick);
    };
  }, [isLink]);
  const valueElement = isLink ? /* @__PURE__ */ react_default.createElement(
    StyledLink,
    {
      role: "button",
      elementRef: ref,
      onClick: (e) => {
        e.preventDefault();
        onFieldValueClicked(e, { field, value });
      }
    },
    value
  ) : /* @__PURE__ */ react_default.createElement("span", null, value);
  return /* @__PURE__ */ react_default.createElement(FieldValueContainer, { $highlighted: isHighlighted }, valueElement);
};
var MaybeTagsLink = (props) => {
  const { field, onTagClicked, tags } = props;
  if (!tags || tags.length === 0) {
    return /* @__PURE__ */ react_default.createElement("span", null);
  }
  if (onTagClicked) {
    return /* @__PURE__ */ react_default.createElement(react_default.Fragment, null, "\xA0( ", tags.map((tag) => /* @__PURE__ */ react_default.createElement("span", { key: (0, id_exports.createDOMID)() }, /* @__PURE__ */ react_default.createElement(
      StyledLink,
      {
        role: "button",
        onClick: (e) => {
          e.preventDefault();
          onTagClicked(e, { field, value: tag });
        }
      },
      tag
    ), "\xA0")), ")");
  }
  return /* @__PURE__ */ react_default.createElement("span", null, "\xA0(\xA0", tags.join(" "), "\xA0)\xA0");
};

// src/components/FooterFields/index.tsx
var FooterFieldList = styled_components_default.dl`
    padding: 0;
    margin: 0;
`;
var FooterField = styled_components_default.div`
    &:not(:last-of-type) {
        border-right: 1px dashed ${themes_exports.variables.borderColor};
    }
    margin-right: ${themes_exports.variables.spacingSmall};
    list-style: none;
    display: inline;
`;
var FooterItem = styled_components_default.span`
    display: inline;
    margin: 0;
    padding: 0;
    color: ${themes_exports.variables.contentColorDefault};
`;
var FooterFields = (props) => {
  const { footerFields, fieldValueHighlightMap, allTagsMap } = props;
  const uniqueFooterFields = react_default.useMemo(() => {
    const fieldsThatExist = footerFields == null ? void 0 : footerFields.filter((field) => has_default(props.event, field));
    return [...new Set(fieldsThatExist)];
  }, [footerFields, props.event]);
  const featureFlagContext = react_default.useContext(FeatureFlagContext_default);
  const isTagFeatureFlagOn = featureFlagContext == null ? void 0 : featureFlagContext.visualizations_enableEventsViewerTags;
  const renderFooterField = (field, value) => {
    var _a;
    const valuesToHighlight = fieldValueHighlightMap == null ? void 0 : fieldValueHighlightMap[field];
    let isValueHighlighted = false;
    if (valuesToHighlight) {
      if (Array.isArray(valuesToHighlight)) {
        isValueHighlighted = valuesToHighlight.findIndex((v1) => {
          return testStringWithWildCardString(v1.toString(), value);
        }) > -1;
      } else {
        isValueHighlighted = testStringWithWildCardString(valuesToHighlight.toString(), value);
      }
    }
    const tagsKey = `${field}=${value}`;
    return /* @__PURE__ */ react_default.createElement(react_default.Fragment, { key: `${field}=${value}` }, /* @__PURE__ */ react_default.createElement(FooterItem, null, field, " ", /* @__PURE__ */ react_default.createElement("span", { "aria-hidden": "true" }, "="), " "), /* @__PURE__ */ react_default.createElement(FooterItem, null, /* @__PURE__ */ react_default.createElement(
      MaybeFieldValueLink,
      {
        field,
        value,
        onFieldValueClicked: props.onFieldValueClicked,
        isField: props.isField,
        isHighlighted: isValueHighlighted
      }
    ), isTagFeatureFlagOn && /* @__PURE__ */ react_default.createElement(
      MaybeTagsLink,
      {
        field,
        onTagClicked: props.onTagClicked,
        tags: (_a = allTagsMap[tagsKey]) != null ? _a : []
      }
    ), " "));
  };
  return /* @__PURE__ */ react_default.createElement(FooterFieldList, null, uniqueFooterFields.map((field) => {
    const value = props.event[field];
    if (!value) {
      return null;
    }
    return /* @__PURE__ */ react_default.createElement(FooterField, { key: `footer-entry-${field}` }, Array.isArray(value) ? value.map((valueItem) => renderFooterField(field, valueItem)) : renderFooterField(field, value));
  }));
};
var FooterFields_default = FooterFields;

// src/components/CustomCell/index.tsx
var TableCell = styled_components_default(Table_default.Cell)`
    font-family: ${themes_exports.variables.monoFontFamily};
    line-height: ${themes_exports.variables.lineHeight};
    div {
        flex-direction: column;
        align-items: flex-start;
        margin: 0;
        padding: 0;
    }
`;
var StyledButton = styled_components_default(Button_default)`
    margin-top: ${themes_exports.variables.spacingLarge};
    margin-bottom: ${themes_exports.variables.spacingXSmall};
    display: block;
    width: fit-content;
`;
var StyledJSONTree = styled_components_default(JSONTree_default)`
    span {
        min-height: 0px;
    }
`;
var JsonCell = class extends react_exports.Component {
  constructor(props) {
    super(props);
    /** Method to set the highlight state to false so that
     * raw event text is displayed in the table cell  */
    __publicField(this, "getRawText", () => {
      this.setState({
        highlight: false
      });
    });
    /** Method to the highlight state to true so that the
     * event is shown as a JSON tree */
    __publicField(this, "highlightSyntax", () => {
      this.setState({
        highlight: true
      });
    });
    this.state = {
      highlight: props.initialHighlight
    };
  }
  render() {
    const { rawEventString, wrapResults: wrapResults2 } = this.props;
    return this.state.highlight ? /* @__PURE__ */ react_default.createElement("div", null, /* @__PURE__ */ react_default.createElement(
      StyledJSONTree,
      {
        json: rawEventString,
        defaultExpanded: false,
        overflow: wrapResults2 ? "wrap" : "scroll"
      }
    ), /* @__PURE__ */ react_default.createElement(
      StyledButton,
      {
        appearance: "standalone",
        onClick: (e) => {
          e.preventDefault();
          this.getRawText();
        },
        "data-test": "show-raw-text-button"
      },
      (0, i18n_exports._)("Show as raw text")
    )) : /* @__PURE__ */ react_default.createElement("div", null, /* @__PURE__ */ react_default.createElement("div", null, rawEventString), /* @__PURE__ */ react_default.createElement(
      StyledButton,
      {
        appearance: "standalone",
        onClick: (e) => {
          e.preventDefault();
          this.highlightSyntax();
        },
        "data-test": "highlight-syntax-button"
      },
      (0, i18n_exports._)("Show syntax highlighted")
    ));
  }
};
var CustomCell = ({
  wrapResults: wrapResults2,
  initialHighlight,
  rawEventString,
  event,
  showFooter,
  footerFields,
  fieldValueHighlightMap,
  allTagsMap,
  onFieldValueClicked,
  onTagClicked,
  isField
}) => /* @__PURE__ */ react_default.createElement(TableCell, { style: wrapResults2 ? {} : { whiteSpace: "nowrap" } }, isJsonString(rawEventString) ? /* @__PURE__ */ react_default.createElement(
  JsonCell,
  {
    initialHighlight,
    rawEventString,
    wrapResults: wrapResults2
  }
) : rawEventString, showFooter && /* @__PURE__ */ react_default.createElement(
  FooterFields_default,
  {
    event,
    footerFields,
    fieldValueHighlightMap,
    onFieldValueClicked,
    onTagClicked,
    isField,
    allTagsMap
  }
));
var CustomCell_default = CustomCell;

// src/components/Raw/index.tsx
var Raw = ({
  events,
  getExpansionRow,
  pageNumber,
  selection,
  onFieldValueClicked,
  footerFields,
  fieldValueHighlightMap,
  isField
}) => {
  const [expandedRowId, setExpandedRowId] = react_default.useState(null);
  const handleRowExpansion = (rowId) => {
    if (expandedRowId === rowId) {
      setExpandedRowId(null);
    } else {
      setExpandedRowId(rowId);
    }
  };
  return /* @__PURE__ */ react_default.createElement(
    Table_default,
    {
      stripeRows: true,
      rowExpansion: "controlled",
      "data-test": "workflow-components:Raw",
      onRequestToggleAllRows: selection ? () => selection.onTogglePage(events, pageNumber, selection.pageToggle) : void 0,
      rowSelection: selection ? selection.pageToggle : void 0
    },
    /* @__PURE__ */ react_default.createElement(Table_default.Head, null, /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, null, "Event")),
    /* @__PURE__ */ react_default.createElement(Table_default.Body, null, events.map((event, index) => {
      const key = generateKey(event, index, pageNumber);
      const rawEventString = rawString(event);
      return /* @__PURE__ */ react_default.createElement(
        Table_default.Row,
        {
          key,
          expansionRow: getExpansionRow(event, key, index, pageNumber),
          onExpansion: () => handleRowExpansion(key),
          expanded: key === expandedRowId,
          onRequestToggle: selection ? () => selection.onToggleRow(event, index, pageNumber) : void 0,
          selected: selection ? selection.rows.some(
            (row) => row.index === index && row.pageNumber === pageNumber
          ) : void 0,
          rowScreenReaderText: event._time
        },
        /* @__PURE__ */ react_default.createElement(
          CustomCell_default,
          {
            rawEventString,
            initialHighlight: false,
            wrapResults: true,
            event,
            footerFields,
            fieldValueHighlightMap,
            showFooter: key !== expandedRowId,
            onFieldValueClicked,
            isField
          }
        )
      );
    }))
  );
};
var Raw_default = Raw;

// esm-externals:@splunk/moment
var moment_exports = {};
__export(moment_exports, {
  default: () => moment_default
});
var defaultImport18 = __toESM(require("@splunk/moment"));
__reExport(moment_exports, require("@splunk/moment"));
var moment_default = "default" in defaultImport18 ? defaultImport18.default : defaultImport18;

// src/components/TimeValue/index.tsx
var TimeLink = styled_components_default(Link_default)`
    color: ${themes_exports.variables.contentColorDefault};
    line-height: ${themes_exports.variables.lineHeight};

    &:hover,
    &focus {
        color: ${themes_exports.variables.linkColor};
    }
`;
var Part = styled_components_default.span`
    pointer-events: none;
    white-space: nowrap;
`;
var TimeValue = (_a) => {
  var _b = _a, {
    time,
    timeFormat,
    onTimeClicked,
    timeFieldAdditionalProps
  } = _b, rest = __objRest(_b, [
    "time",
    "timeFormat",
    "onTimeClicked",
    "timeFieldAdditionalProps"
  ]);
  if (!time) {
    return null;
  }
  const lmsTimeParts = [
    /* @__PURE__ */ react_default.createElement(Part, { key: "date" }, moment_default(time).splunkFormat("l")),
    /* @__PURE__ */ react_default.createElement("br", { key: "break" }),
    /* @__PURE__ */ react_default.createElement(Part, { key: "time" }, moment_default(time).splunkFormat("LTMS"))
  ];
  const parts = timeFormat === "lms" ? lmsTimeParts : moment_default(time).splunkFormat(timeFormat);
  if (!onTimeClicked) {
    return /* @__PURE__ */ react_default.createElement("span", __spreadValues({ "data-test": "time-value", "data-test-value": time }, rest), parts);
  }
  return /* @__PURE__ */ react_default.createElement(
    TimeLink,
    __spreadValues(__spreadValues({
      role: "button",
      "data-test": "time-value",
      "data-test-value": time,
      onClick: (e) => {
        e.preventDefault();
        onTimeClicked(e, { time });
      }
    }, timeFieldAdditionalProps), rest),
    parts
  );
};
var TimeValue_default = TimeValue;

// esm-externals:@splunk/splunk-utils/fetch
var fetch_exports = {};
__export(fetch_exports, {
  default: () => fetch_default
});
var defaultImport19 = __toESM(require("@splunk/splunk-utils/fetch"));
__reExport(fetch_exports, require("@splunk/splunk-utils/fetch"));
var fetch_default = "default" in defaultImport19 ? defaultImport19.default : defaultImport19;

// esm-externals:@splunk/splunk-utils/config
var config_exports = {};
__export(config_exports, {
  default: () => config_default
});
var defaultImport20 = __toESM(require("@splunk/splunk-utils/config"));
__reExport(config_exports, require("@splunk/splunk-utils/config"));
var config_default = "default" in defaultImport20 ? defaultImport20.default : defaultImport20;

// esm-externals:@splunk/splunk-utils/url
var url_exports = {};
__export(url_exports, {
  default: () => url_default
});
var defaultImport21 = __toESM(require("@splunk/splunk-utils/url"));
__reExport(url_exports, require("@splunk/splunk-utils/url"));
var url_default = "default" in defaultImport21 ? defaultImport21.default : defaultImport21;

// src/utils/tagAPI.ts
var tagsURL = `/servicesNS/${encodeURIComponent(config_exports.username)}/${encodeURIComponent(config_exports.app)}/saved/fvtags`;
var getTagsHash = (tags) => {
  return tags.reduce((hash, tag) => {
    hash[`tag.${tag}`] = tag;
    return hash;
  }, {});
};
var handleResponse = (response, expectedStatus = 200) => __async(void 0, null, function* () {
  var _a;
  if (!(response == null ? void 0 : response.ok)) {
    const defaultErrorMsg = `${response == null ? void 0 : response.status} - ${response == null ? void 0 : response.statusText}`;
    const JSONErrorMsg = (0, fetch_exports.findErrorMessage)(yield response == null ? void 0 : response.json());
    const error = new Error((_a = JSONErrorMsg == null ? void 0 : JSONErrorMsg.text) != null ? _a : defaultErrorMsg);
    throw error;
  }
  if (response.status !== expectedStatus) {
    throw new Error(`Received status code ${response.status} instead of expected ${expectedStatus}`);
  }
  return response.json();
});
var fetchRESTURL = (..._0) => __async(void 0, [..._0], function* (url = "", namespace = {}, queryParams = {}, fetchParams = {}, responseCode = 200) {
  const queryParamsObj = new URLSearchParams(queryParams);
  const validQueryParams = JSON.stringify(queryParams) === "{}" ? "" : `?${queryParamsObj.toString()}`;
  const splunkURL = (0, url_exports.createRESTURL)(url, namespace);
  const fetchArgs = __spreadValues(__spreadValues({}, fetch_exports.defaultFetchInit), fetchParams);
  const response = yield fetch(`${splunkURL}${validQueryParams}`, fetchArgs);
  return handleResponse(response, responseCode);
});
var fetchTags = (fname = "", fvalue = "") => __async(void 0, null, function* () {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {
      output_mode: "json"
    },
    { method: "GET" }
  );
  return result.entry[0].content.tags;
});
var fetchAllTags = () => __async(void 0, null, function* () {
  const url = tagsURL;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    { output_mode: "json", count: 0 },
    { method: "GET" }
  );
  return result.entry.reduce((fvTagsMap, tagObject) => {
    if (!tagObject.content.disabled) {
      fvTagsMap[tagObject.name] = tagObject.content.tags;
    }
    return fvTagsMap;
  }, {});
});
var createTags = (..._0) => __async(void 0, [..._0], function* (fname = "", fvalue = "", tags = []) {
  const url = tagsURL;
  const data = __spreadValues({
    name: `${fname}=${fvalue}`,
    output_mode: "json"
  }, getTagsHash(tags));
  const dataObj = new URLSearchParams(data);
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {},
    {
      method: "POST",
      body: dataObj.toString()
    },
    201
  );
  return result.entry[0].content.tags;
});
var updateTags = (..._0) => __async(void 0, [..._0], function* (fname = "", fvalue = "", tags = []) {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const data = __spreadValues({
    output_mode: "json"
  }, getTagsHash(tags));
  const dataObj = new URLSearchParams(data);
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    {},
    {
      method: "POST",
      body: dataObj.toString()
    }
  );
  return result.entry[0].content.tags;
});
var deleteTags = (fname = "", fvalue = "") => __async(void 0, null, function* () {
  const url = `${tagsURL}/${encodeURIComponent(fname)}%3D${encodeURIComponent(fvalue)}`;
  const result = yield fetchRESTURL(
    url,
    {
      app: config_exports.app,
      username: config_exports.username
    },
    { output_mode: "json" },
    { method: "DELETE" }
  );
  return result.entry;
});
var flattenTagObject = (tags) => {
  const flattenedTags = {};
  const fields = tags ? Object.keys(tags) : [];
  fields.forEach((field) => {
    const fieldValues = Object.keys(tags[field]);
    fieldValues.forEach((fieldValue) => {
      const tagsList = tags[field][fieldValue];
      flattenedTags[`${field}=${fieldValue}`] = tagsList;
    });
  });
  return flattenedTags;
};

// src/components/List/index.tsx
var TableRow = styled_components_default(Table_default.Row)`
    td {
        vertical-align: top;
    }

    /* HACK to work around http://go/j/SUI-2413, and also make expand button the full height of the row*/
    td[data-test='expand'] {
        svg {
            width: 32px;
            margin-top: 6px;
        }
        button {
            height: 100%;
            display: flex;
            align-items: flex-start;
        }
    }
`;
var StyledTableHeadCell = styled_components_default(Table_default.HeadCell)`
    span {
        font-size: ${themes_exports.mixins.typography({ size: 14 })};
    }
`;
var List = (_a) => {
  var _b = _a, {
    events,
    getExpansionRow,
    timeFormat = "lms",
    pageNumber,
    rowNumbers: rowNumbers2,
    wrapResults: wrapResults2,
    selection,
    onTimeClicked,
    onFieldValueClicked,
    onTagClicked,
    isField,
    footerFields,
    fieldValueHighlightMap,
    allTagsMap,
    timeFieldAdditionalProps,
    updateAllTags
  } = _b, otherProps = __objRest(_b, [
    "events",
    "getExpansionRow",
    "timeFormat",
    "pageNumber",
    "rowNumbers",
    "wrapResults",
    "selection",
    "onTimeClicked",
    "onFieldValueClicked",
    "onTagClicked",
    "isField",
    "footerFields",
    "fieldValueHighlightMap",
    "allTagsMap",
    "timeFieldAdditionalProps",
    "updateAllTags"
  ]);
  const featureFlagContext = (0, react_exports.useContext)(FeatureFlagContext_default);
  const isTagFeatureFlagOn = featureFlagContext == null ? void 0 : featureFlagContext.visualizations_enableEventsViewerTags;
  const [expandedRowId, setExpandedRowId] = react_default.useState(null);
  const getAllTags = () => __async(void 0, null, function* () {
    try {
      if (isTagFeatureFlagOn) {
        const result = yield fetchAllTags();
        updateAllTags(result);
      }
    } catch (e) {
      console.error(e);
    }
  });
  const handleRowExpansion = (rowId) => {
    if (expandedRowId === rowId) {
      setExpandedRowId(null);
    } else {
      setExpandedRowId(rowId);
    }
    getAllTags();
  };
  return /* @__PURE__ */ react_default.createElement(
    Table_default,
    __spreadValues({
      stripeRows: true,
      rowExpansion: "controlled",
      "data-test": "workflow-components:List",
      onRequestToggleAllRows: selection ? () => selection.onTogglePage(events, pageNumber, selection.pageToggle) : void 0,
      rowSelection: selection ? selection.pageToggle : void 0
    }, otherProps),
    /* @__PURE__ */ react_default.createElement(Table_default.Head, null, /* @__PURE__ */ react_default.createElement(StyledTableHeadCell, null, (0, i18n_exports._)("Time")), rowNumbers2 && /* @__PURE__ */ react_default.createElement(StyledTableHeadCell, { "data-test": "head-cell-rowNumbers" }), /* @__PURE__ */ react_default.createElement(StyledTableHeadCell, null, (0, i18n_exports._)("Event"))),
    /* @__PURE__ */ react_default.createElement(Table_default.Body, null, events.map((event, index) => {
      const key = generateKey(event, index, pageNumber);
      const rawEventString = rawString(event);
      return /* @__PURE__ */ react_default.createElement(
        TableRow,
        {
          key,
          expansionRow: getExpansionRow(event, key, index, pageNumber),
          onExpansion: () => handleRowExpansion(key),
          expanded: key === expandedRowId,
          onRequestToggle: selection ? () => selection.onToggleRow(event, index, pageNumber) : void 0,
          selected: selection ? selection.rows.some(
            (row) => row.index === index && row.pageNumber === pageNumber
          ) : void 0,
          rowScreenReaderText: event._time
        },
        /* @__PURE__ */ react_default.createElement(Table_default.Cell, null, /* @__PURE__ */ react_default.createElement(
          TimeValue_default,
          {
            time: event._time,
            timeFormat,
            onTimeClicked,
            timeFieldAdditionalProps
          }
        )),
        rowNumbers2 && /* @__PURE__ */ react_default.createElement(Table_default.Cell, null, index + 1),
        /* @__PURE__ */ react_default.createElement(
          CustomCell_default,
          {
            rawEventString,
            wrapResults: wrapResults2,
            initialHighlight: true,
            event,
            footerFields,
            fieldValueHighlightMap,
            showFooter: key !== expandedRowId,
            onFieldValueClicked,
            onTagClicked,
            isField,
            allTagsMap
          }
        )
      );
    }))
  );
};
var List_default = List;

// esm-externals:lodash/isArray
var isArray_exports = {};
__export(isArray_exports, {
  default: () => isArray_default
});
var defaultImport22 = __toESM(require("lodash/isArray"));
__reExport(isArray_exports, require("lodash/isArray"));
var isArray_default = "default" in defaultImport22 ? defaultImport22.default : defaultImport22;

// esm-externals:lodash/isObject
var isObject_exports = {};
__export(isObject_exports, {
  default: () => isObject_default
});
var defaultImport23 = __toESM(require("lodash/isObject"));
__reExport(isObject_exports, require("lodash/isObject"));
var isObject_default = "default" in defaultImport23 ? defaultImport23.default : defaultImport23;

// src/components/EventsTable/index.tsx
var TableRow2 = styled_components_default(Table_default.Row)`
    td {
        vertical-align: top;
    }

    /* HACK to work around http://go/j/SUI-2413 */
    td[data-role='expand'] {
        svg {
            width: 32px;
        }
    }
`;
var EventsTable = (_a) => {
  var _b = _a, {
    fields,
    events,
    pageNumber,
    getExpansionRow,
    timeFormat,
    rowNumbers: rowNumbers2,
    selection,
    onTimeClicked,
    timeFieldAdditionalProps
  } = _b, otherProps = __objRest(_b, [
    "fields",
    "events",
    "pageNumber",
    "getExpansionRow",
    "timeFormat",
    "rowNumbers",
    "selection",
    "onTimeClicked",
    "timeFieldAdditionalProps"
  ]);
  const columns = fields.reduce((agg, { name }) => {
    if (isTimeField(name)) {
      agg.unshift(name);
    } else if (!isInternalField(name)) {
      agg.push(name);
    }
    return agg;
  }, []);
  return /* @__PURE__ */ react_default.createElement(
    Table_default,
    __spreadValues({
      stripeRows: true,
      rowExpansion: "single",
      "data-test": "workflow-components:EventsTable",
      onRequestToggleAllRows: selection ? () => selection.onTogglePage(events, pageNumber, selection.pageToggle) : void 0,
      rowSelection: selection ? selection.pageToggle : void 0
    }, otherProps),
    /* @__PURE__ */ react_default.createElement(Table_default.Head, null, rowNumbers2 && /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { key: "row-numbers", style: { width: 10 } }, " "), columns.map((column) => /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { key: `field-${column}` }, isTimeField(column) ? (0, i18n_exports._)("Time") : column))),
    /* @__PURE__ */ react_default.createElement(Table_default.Body, null, events.map((event, index) => {
      const key = generateKey(event, index, pageNumber);
      return /* @__PURE__ */ react_default.createElement(
        TableRow2,
        {
          key,
          expansionRow: getExpansionRow(event, key, index, pageNumber),
          onRequestToggle: selection ? () => selection.onToggleRow(event, index, pageNumber) : void 0,
          selected: selection ? selection.rows.some(
            (row) => row.index === index && row.pageNumber === pageNumber
          ) : void 0,
          rowScreenReaderText: event._time
        },
        rowNumbers2 && /* @__PURE__ */ react_default.createElement(Table_default.Cell, null, index + 1),
        columns.map((column) => {
          let cellVal = event[column];
          if (isTimeField(column)) {
            cellVal = /* @__PURE__ */ react_default.createElement(
              TimeValue_default,
              {
                time: event._time,
                timeFormat,
                onTimeClicked,
                timeFieldAdditionalProps
              }
            );
          } else if (isArray_default(cellVal) || isObject_default(cellVal)) {
            cellVal = JSON.stringify(cellVal);
          }
          return /* @__PURE__ */ react_default.createElement(Table_default.Cell, { key: `${column}-${key}` }, cellVal);
        })
      );
    }))
  );
};
EventsTable.defaultProps = {
  timeFormat: "lms"
};
var EventsTable_default = EventsTable;

// src/utils/TableStyleSet.ts
var _TableStyleSet = class _TableStyleSet {
  // NOSONAR - assigned after class definition
  /**
   * Create a TableStyles object
   *
   * @param {Array} styles An array of styles.
   * When displayed to the user, the order of this
   * array will be preserved.
   *
   * @returns {TableStyles}
   */
  constructor(styles) {
    __publicField(this, "data", {
      // NOSONAR
      styles: [],
      dict: {}
    });
    this.data.styles = styles.slice();
    this.data.styles.forEach((style) => {
      this.data.dict[style.key] = style;
      if ([style.key, style.label, style.component].includes(void 0)) {
        throw Error("All table style definitions must have key, label, and component fields");
      }
    });
  }
  /**
   * Return all table style definitions from this set
   * @returns {Array} The table style definitions, in the same order they were defined.
   */
  getValues() {
    return this.data.styles.slice();
  }
  /**
   * Return all table style keys
   * @returns {Array} The keys
   */
  getKeys() {
    return this.data.styles.map((s) => s.key);
  }
  /**
   * Get a table style definition by its key
   * @param {String} key The key for the desired table style
   * @returns {Object} The table style definition requested
   */
  get(key) {
    return this.data.dict[key];
  }
  /**
   * Create a new table style set that is a concatenation of the table styles
   * from this set, plus those from the styles param, in that order.
   *
   * Intended to simplify the simple use case that a client would like to append some
   * custom table styles to the `TableStyleSet.builtin` set. For clients that would
   * like to include only some builtin styles, or would like to re-order them, it may
   * be helpful to grab the desired styles with `TableStyleSet.builtin.get(key)`,
   * and then create the TableStyleSet with the desired order manually.
   *
   * @param {(Array|TableStyleSet)} styles The styles to concatenate with this set.
   * @returns {TableStyleSet} The new TableStyleSet
   */
  concat(styles) {
    if (styles instanceof _TableStyleSet) {
      return new _TableStyleSet(this.data.styles.concat(styles.getValues()));
    }
    return new _TableStyleSet(this.data.styles.concat(styles));
  }
};
__publicField(_TableStyleSet, "builtin");
var TableStyleSet = _TableStyleSet;
var wrapResults = {
  key: "wrapResults",
  label: (0, i18n_exports._)("Wrap Results")
};
var rowNumbers = {
  key: "rowNumbers",
  label: (0, i18n_exports._)("Row Numbers")
};
var buildtinStyles = [
  {
    key: "raw",
    label: (0, i18n_exports._)("Raw"),
    component: Raw_default,
    formattingOptions: []
  },
  {
    key: "list",
    label: (0, i18n_exports._)("List"),
    component: List_default,
    formattingOptions: [wrapResults, rowNumbers]
  },
  {
    key: "table",
    label: (0, i18n_exports._)("Table"),
    component: EventsTable_default,
    formattingOptions: [wrapResults, rowNumbers]
  }
];
TableStyleSet.builtin = new TableStyleSet(buildtinStyles);

// src/utils/pagination.ts
function getOffset(page = 1, count = 0) {
  return (page - 1) * count;
}

// src/components/ConfigurationPanel/SelectionButtons.tsx
var Container = styled_components_default.div`
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    /* Could just be button, other props added to win the specificity war */
    /* This is adding margin so that when the buttons wrap they have space between them */
    & > button[data-inline]:not([data-prepend]) {
        margin-right: ${themes_exports.variables.spacingSmall};
    }
    & > [data-inline] + button[data-inline]:not([data-prepend]) {
        margin: ${themes_exports.variables.spacingXSmall} ${themes_exports.variables.spacingSmall} ${themes_exports.variables.spacingXSmall} 0;
    }

    button {
        flex-grow: 0;
    }

    & > span {
        margin: ${themes_exports.variables.spacingXSmall} 0;
    }
`;
var SelectionButtons = (_a) => {
  var _b = _a, {
    selectionCount,
    actions,
    onActionClicked
  } = _b, otherProps = __objRest(_b, [
    "selectionCount",
    "actions",
    "onActionClicked"
  ]);
  return /* @__PURE__ */ react_default.createElement(Container, __spreadValues({ "data-test": "selection-buttons" }, otherProps), actions.map(({ label, name }) => /* @__PURE__ */ react_default.createElement(
    Button_default,
    {
      key: name,
      "data-test": name,
      label,
      disabled: selectionCount === 0,
      appearance: "default",
      onClick: (e) => onActionClicked(e, { action: name })
    }
  )), /* @__PURE__ */ react_default.createElement("span", null, (0, format_exports.sprintf)((0, i18n_exports._)("%(selectionCount)d Selected"), { selectionCount })));
};
var SelectionButtons_default = SelectionButtons;

// esm-externals:@splunk/react-icons/enterprise/Paintbrush
var Paintbrush_exports = {};
__export(Paintbrush_exports, {
  default: () => Paintbrush_default
});
var defaultImport24 = __toESM(require("@splunk/react-icons/enterprise/Paintbrush"));
__reExport(Paintbrush_exports, require("@splunk/react-icons/enterprise/Paintbrush"));
var Paintbrush_default = "default" in defaultImport24 ? defaultImport24.default : defaultImport24;

// src/components/ConfigurationPanel/TableFormatter.tsx
var FormattingOption = ({ name, label, selected, onOptionsChange }) => {
  const key = name;
  return /* @__PURE__ */ react_default.createElement(
    Menu_default.Item,
    {
      "data-test": key,
      value: key,
      onClick: () => onOptionsChange({ [key]: !selected }),
      selected,
      selectable: true
    },
    label
  );
};
var TableFormatter = ({
  tableStyle,
  formattingOptions,
  formattingValues,
  onOptionsChange
}) => {
  const toggle = /* @__PURE__ */ react_default.createElement(
    Button_default,
    {
      icon: /* @__PURE__ */ react_default.createElement(Paintbrush_default, { screenReaderText: "" }),
      label: (0, i18n_exports._)("Format"),
      appearance: "subtle",
      "data-test": "table-formatter-button",
      isMenu: true
    }
  );
  const availableOptions = formattingOptions.reduce((agg, option) => {
    const found = tableStyle.formattingOptions.find(({ key }) => key === option);
    if (found) {
      agg.push(found);
    }
    return agg;
  }, []);
  if (availableOptions.length === 0) {
    return null;
  }
  return /* @__PURE__ */ react_default.createElement(Dropdown_default, { toggle }, /* @__PURE__ */ react_default.createElement(Menu_default, { "data-test": "table-format-menu" }, availableOptions.map(({ key, label }) => /* @__PURE__ */ react_default.createElement(
    FormattingOption,
    {
      key,
      name: key,
      label,
      selected: formattingValues[key],
      onOptionsChange
    }
  ))));
};
var TableFormatter_default = TableFormatter;

// src/components/ConfigurationPanel/index.tsx
var ConfigurationPanel = ({
  showPagination = true,
  tableStyles = TableStyleSet.builtin,
  pagination,
  style = {},
  formattingOptions = [],
  formattingValues,
  currentTableStyle,
  onRequestParamsChange,
  requestParams,
  onOptionsChange,
  selectionActions,
  selectionCount,
  onSelectionActionClicked
}) => {
  const paginatorProps = {
    totalPages: pagination.totalPages,
    current: pagination.page,
    onChange: onRequestParamsChange
  };
  const handlePageChange = (e, { page }) => {
    const { pageLength } = pagination;
    onRequestParamsChange("primary", __spreadValues(__spreadValues({}, requestParams), { offset: getOffset(page, pageLength), count: pageLength }));
  };
  const handlePageLengthChange = (e, { value }) => {
    onRequestParamsChange("primary", __spreadValues(__spreadValues({}, requestParams), { count: value, offset: 0 }));
  };
  const handleTableStyleChanged = (e, { value }) => {
    onOptionsChange({ currentTableStyle: value });
  };
  const styles = {
    controlsContainer: {
      display: "flex",
      alignItems: "flex-end"
    },
    controlsSeparator: {
      flexGrow: 1
    }
  };
  const renderTableStyleSelector = () => {
    if (currentTableStyle === null || currentTableStyle === void 0) {
      return null;
    }
    const tableStyle = tableStyles.get(currentTableStyle);
    const toggle = /* @__PURE__ */ react_default.createElement(
      Button_default,
      {
        label: tableStyle.label,
        appearance: "subtle",
        isMenu: true,
        "data-test": "table-style-selector-button"
      }
    );
    return /* @__PURE__ */ react_default.createElement("div", { key: "table-styles" }, /* @__PURE__ */ react_default.createElement(Dropdown_default, { toggle }, /* @__PURE__ */ react_default.createElement(Menu_default, { style: menu, "data-test": "table-style-selector-dropdown" }, tableStyles.getValues().map((styleValue) => /* @__PURE__ */ react_default.createElement(
      ValueMenuItem,
      {
        key: styleValue.key,
        onClick: handleTableStyleChanged,
        value: styleValue.key,
        selectable: true,
        selected: styleValue.key === currentTableStyle
      },
      /* @__PURE__ */ react_default.createElement("span", null, styleValue.label)
    )))));
  };
  const renderTableFormatter = () => {
    if (!currentTableStyle) {
      return null;
    }
    const tableStyle = tableStyles.get(currentTableStyle);
    return /* @__PURE__ */ react_default.createElement("div", { key: "table-formatter" }, /* @__PURE__ */ react_default.createElement(
      TableFormatter_default,
      {
        tableStyle,
        formattingOptions,
        formattingValues,
        onOptionsChange
      }
    ));
  };
  const renderPageLengthSelector = () => {
    if (showPagination && pagination.pageLengthOptions.length > 0) {
      return /* @__PURE__ */ react_default.createElement("div", { key: "page-length-selector" }, /* @__PURE__ */ react_default.createElement(
        PageLengthSelector_default,
        {
          pageLength: pagination.pageLength,
          options: pagination.pageLengthOptions,
          onChange: handlePageLengthChange
        }
      ));
    }
    return null;
  };
  const renderPaginator = () => {
    if (showPagination) {
      return /* @__PURE__ */ react_default.createElement(Paginator_default, __spreadProps(__spreadValues({ style: styles.paginator }, paginatorProps), { onChange: handlePageChange }));
    }
    return null;
  };
  const renderSelectionActions = () => /* @__PURE__ */ react_default.createElement(
    SelectionButtons_default,
    {
      actions: selectionActions,
      selectionCount,
      onActionClicked: onSelectionActionClicked
    }
  );
  const tableStyleSelector = renderTableStyleSelector();
  const tableFormatter = renderTableFormatter();
  const pageLengthSelector = renderPageLengthSelector();
  const paginator = renderPaginator();
  if (!(tableStyleSelector || tableFormatter || pageLengthSelector || paginator)) {
    return null;
  }
  return /* @__PURE__ */ react_default.createElement(
    "div",
    {
      "data-test": "workflow-components:ConfigurationPanel",
      style: __spreadValues(__spreadValues({}, styles.controlsContainer), style)
    },
    selectionCount && selectionActions ? renderSelectionActions() : [tableStyleSelector, tableFormatter, pageLengthSelector],
    /* @__PURE__ */ react_default.createElement("div", { style: styles.controlsSeparator }),
    paginator
  );
};
var ConfigurationPanel_default = ConfigurationPanel;

// esm-externals:@splunk/react-ui/Switch
var Switch_exports = {};
__export(Switch_exports, {
  default: () => Switch_default
});
var defaultImport25 = __toESM(require("@splunk/react-ui/Switch"));
__reExport(Switch_exports, require("@splunk/react-ui/Switch"));
var Switch_default = "default" in defaultImport25 ? defaultImport25.default : defaultImport25;

// esm-externals:@splunk/react-icons/enterprise/ChevronDown
var ChevronDown_exports = {};
__export(ChevronDown_exports, {
  default: () => ChevronDown_default
});
var defaultImport26 = __toESM(require("@splunk/react-icons/enterprise/ChevronDown"));
__reExport(ChevronDown_exports, require("@splunk/react-icons/enterprise/ChevronDown"));
var ChevronDown_default = "default" in defaultImport26 ? defaultImport26.default : defaultImport26;

// esm-externals:@splunk/react-ui/ControlGroup
var ControlGroup_exports = {};
__export(ControlGroup_exports, {
  default: () => ControlGroup_default
});
var defaultImport27 = __toESM(require("@splunk/react-ui/ControlGroup"));
__reExport(ControlGroup_exports, require("@splunk/react-ui/ControlGroup"));
var ControlGroup_default = "default" in defaultImport27 ? defaultImport27.default : defaultImport27;

// esm-externals:@splunk/react-ui/Modal
var Modal_exports = {};
__export(Modal_exports, {
  default: () => Modal_default
});
var defaultImport28 = __toESM(require("@splunk/react-ui/Modal"));
__reExport(Modal_exports, require("@splunk/react-ui/Modal"));
var Modal_default = "default" in defaultImport28 ? defaultImport28.default : defaultImport28;

// esm-externals:@splunk/react-ui/TextArea
var TextArea_exports = {};
__export(TextArea_exports, {
  default: () => TextArea_default
});
var defaultImport29 = __toESM(require("@splunk/react-ui/TextArea"));
__reExport(TextArea_exports, require("@splunk/react-ui/TextArea"));
var TextArea_default = "default" in defaultImport29 ? defaultImport29.default : defaultImport29;

// esm-externals:@splunk/react-ui/ComboBox
var ComboBox_exports = {};
__export(ComboBox_exports, {
  default: () => ComboBox_default
});
var defaultImport30 = __toESM(require("@splunk/react-ui/ComboBox"));
__reExport(ComboBox_exports, require("@splunk/react-ui/ComboBox"));
var ComboBox_default = "default" in defaultImport30 ? defaultImport30.default : defaultImport30;

// esm-externals:@splunk/react-ui/Message
var Message_exports = {};
__export(Message_exports, {
  default: () => Message_default
});
var defaultImport31 = __toESM(require("@splunk/react-ui/Message"));
__reExport(Message_exports, require("@splunk/react-ui/Message"));
var Message_default = "default" in defaultImport31 ? defaultImport31.default : defaultImport31;

// src/components/EditTagsModal/index.tsx
var formatTagsToArray = (tagsString) => {
  return tagsString ? tagsString.trim().replace(/,/g, " ").split(/\s+/) : [];
};
var EditTagsModal = (props) => {
  var _a;
  const { fieldName, fieldValue, tags, isOpen, updateIsModalOpen, updateAllTags } = props;
  const formattedTags = (_a = tags == null ? void 0 : tags.join(", ")) != null ? _a : "";
  const [tagsString, setTagsString] = (0, react_exports.useState)(formattedTags);
  const [errorMessage, setErrorMessage] = (0, react_exports.useState)("");
  const [isNew, setIsNew] = (0, react_exports.useState)(!tags);
  const handleRequestClose = () => {
    updateIsModalOpen(false);
  };
  const handleSave = () => __async(void 0, null, function* () {
    setErrorMessage("");
    const tagArray = formatTagsToArray(tagsString);
    try {
      if (isNew) {
        yield createTags(fieldName, fieldValue, tagArray);
      } else if (tagArray.length === 0) {
        yield deleteTags(fieldName, fieldValue);
      } else {
        yield updateTags(fieldName, fieldValue, tagArray);
      }
      handleRequestClose();
      const allTags = yield fetchAllTags();
      updateAllTags(allTags);
    } catch (e) {
      setErrorMessage(e.message);
    }
  });
  const onChange = (e) => {
    const tagString = e.target.value;
    setTagsString(tagString);
  };
  const TEXT = {
    TITLE: (0, i18n_exports._)("Create tags"),
    FIELD_LABEL: (0, i18n_exports._)("Field value"),
    TAGS_LABEL: (0, i18n_exports._)("Tag(s)"),
    HELP: (0, i18n_exports._)("Comma or space separated list of tags."),
    CANCEL: (0, i18n_exports._)("Cancel"),
    SAVE: (0, i18n_exports._)("Save"),
    FIELD_PLACEHOLDER: `${fieldName}=${fieldValue}`
  };
  (0, react_exports.useEffect)(() => {
    const resetModal = () => {
      setErrorMessage("");
      setTagsString(formattedTags);
    };
    const checkTagsExist = () => __async(void 0, null, function* () {
      var _a2;
      try {
        const tagsIncludingDisabled = yield fetchTags(fieldName, fieldValue);
        setTagsString((_a2 = tagsIncludingDisabled == null ? void 0 : tagsIncludingDisabled.join(", ")) != null ? _a2 : "");
        setIsNew(false);
      } catch (e) {
        setIsNew(true);
      }
    });
    if (isOpen) {
      resetModal();
      checkTagsExist();
    }
  }, [isOpen, fieldName, fieldValue, formattedTags]);
  return /* @__PURE__ */ react_default.createElement(
    Modal_default,
    {
      "data-test": "edit-tags-modal",
      onRequestClose: handleRequestClose,
      open: isOpen,
      style: { width: "550px" },
      onClick: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      onMouseDown: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      onMouseUp: (syntheticEvent) => {
        syntheticEvent.stopPropagation();
      },
      returnFocus: () => {
      }
    },
    /* @__PURE__ */ react_default.createElement(Modal_default.Header, { title: TEXT.TITLE }),
    /* @__PURE__ */ react_default.createElement(Modal_default.Body, null, errorMessage && /* @__PURE__ */ react_default.createElement(Message_default, { type: "error" }, errorMessage), /* @__PURE__ */ react_default.createElement(ControlGroup_default, { label: TEXT.FIELD_LABEL }, /* @__PURE__ */ react_default.createElement(
      ComboBox_default,
      {
        "data-test": "edit-tags-modal-field",
        disabled: true,
        placeholder: TEXT.FIELD_PLACEHOLDER
      }
    )), /* @__PURE__ */ react_default.createElement(ControlGroup_default, { label: TEXT.TAGS_LABEL, help: TEXT.HELP }, /* @__PURE__ */ react_default.createElement(TextArea_default, { "data-test": "edit-tags-modal-textarea", value: tagsString, onChange }))),
    /* @__PURE__ */ react_default.createElement(Modal_default.Footer, null, /* @__PURE__ */ react_default.createElement(Button_default, { appearance: "secondary", onClick: handleRequestClose, label: TEXT.CANCEL }), /* @__PURE__ */ react_default.createElement(Button_default, { appearance: "primary", onClick: handleSave, label: TEXT.SAVE }))
  );
};
var EditTagsModal_default = EditTagsModal;

// src/components/RowExpander/index.tsx
var TableHead = styled_components_default(Table_default.Head)`
    border-bottom: 1px solid ${themes_exports.variables.borderColorWeak};
`;
var TableRow3 = styled_components_default(Table_default.Row)`
    border-bottom: 1px solid ${themes_exports.variables.borderColorWeak};
`;
var StyledSpan = styled_components_default.span`
    font-size: ${themes_exports.mixins.typography({ size: 14 })};
    font-weight: ${themes_exports.mixins.typography({ weight: "bold" })};
    white-space: nowrap;
`;
var StyledTableCell = styled_components_default(Table_default.Cell)`
    padding: 0 0 0 15px;
    div {
        min-height: 0;
    }
`;
var StyledWrapper = styled_components_default.div`
    width: 100%;
`;
var RowExpander = (_a) => {
  var _b = _a, {
    renderEventActions = [],
    renderFieldActions = {},
    fieldValueHighlightMap = {},
    allTagsMap = {},
    updateAllTags,
    event,
    onFieldValueClicked,
    isField,
    onTagClicked,
    index,
    pageNumber,
    onFieldClicked,
    onTimeClicked,
    timeFieldAdditionalProps,
    fieldAdditionalProps
  } = _b, otherProps = __objRest(_b, [
    "renderEventActions",
    "renderFieldActions",
    "fieldValueHighlightMap",
    "allTagsMap",
    "updateAllTags",
    "event",
    "onFieldValueClicked",
    "isField",
    "onTagClicked",
    "index",
    "pageNumber",
    "onFieldClicked",
    "onTimeClicked",
    "timeFieldAdditionalProps",
    "fieldAdditionalProps"
  ]);
  const featureFlagContext = (0, react_exports.useContext)(FeatureFlagContext_default);
  const isTagFeatureFlagOn = featureFlagContext == null ? void 0 : featureFlagContext.visualizations_enableEventsViewerTags;
  const [editTagsModalData, setEditTagsModalData] = (0, react_exports.useState)({
    isOpen: false,
    fieldName: "",
    fieldValue: "",
    tags: []
  });
  const updateIsModalOpen = (0, react_exports.useCallback)(
    (isOpen) => {
      setEditTagsModalData(__spreadProps(__spreadValues({}, editTagsModalData), { isOpen }));
    },
    [editTagsModalData]
  );
  const updateEditTagsModalData = (0, react_exports.useCallback)(
    (isOpen, fieldName, fieldValue, tags) => {
      setEditTagsModalData({ isOpen, fieldName, fieldValue, tags });
    },
    []
  );
  const eventActionsToggle = /* @__PURE__ */ react_default.createElement(
    Button_default,
    {
      label: (0, i18n_exports._)("Event Actions"),
      isMenu: true,
      style: { marginBottom: 10 },
      "data-test": "event-actions-dropdown"
    }
  );
  const parsedata = (0, lodash_exports.pickBy)(event, (val) => (0, lodash_exports.isString)(val) || (0, lodash_exports.isArray)(val));
  const fields = Object.keys(parsedata).filter((field) => !isInternalField(field));
  const headCellStyle = { backgroundColor: "transparent" };
  const actionCellStyle = { padding: "0 0 0 0" };
  const tableCellDropdownStyle = { marginTop: 3 };
  const haveFieldSelection = false;
  const fieldActionsMap = getFieldActionsMap(event, renderFieldActions, fields);
  const haveFieldActions = Object.keys(fieldActionsMap).length !== 0;
  const haveFieldValueActions = isTagFeatureFlagOn ? true : haveFieldActions;
  const eventActionComponents = getFilteredEventActionComponents(event, renderEventActions);
  const getValueRow = (field, value) => {
    var _a2;
    const valuesToHighlight = fieldValueHighlightMap == null ? void 0 : fieldValueHighlightMap[field];
    let isValueHighlighted = false;
    if (valuesToHighlight) {
      if (Array.isArray(valuesToHighlight)) {
        isValueHighlighted = valuesToHighlight.findIndex((v1) => {
          return testStringWithWildCardString(v1.toString(), value);
        }) > -1;
      } else {
        isValueHighlighted = testStringWithWildCardString(valuesToHighlight.toString(), value);
      }
    }
    const fieldActions = fieldActionsMap[field] || [];
    const tagsKey = `${field}=${value}`;
    if (isTagFeatureFlagOn) {
      const handleModalOpen = () => {
        updateEditTagsModalData(true, field, value, allTagsMap[tagsKey]);
      };
      const editTagsAction = () => /* @__PURE__ */ react_default.createElement(
        Menu_default.Item,
        {
          key: "field-action-edit-tags",
          "data-test": "field-action-edit-tags",
          onClick: handleModalOpen
        },
        (0, i18n_exports._)("Edit tags")
      );
      fieldActions.unshift(editTagsAction);
    }
    const actionToggle = /* @__PURE__ */ react_default.createElement(
      Link_default,
      {
        "data-test": "field-actions-dropdown",
        "aria-label": `${field} actions`,
        style: tableCellDropdownStyle,
        role: "button",
        onClick: (e) => e.preventDefault()
      },
      /* @__PURE__ */ react_default.createElement(ChevronDown_default, { screenReaderText: null })
    );
    return /* @__PURE__ */ react_default.createElement(react_default.Fragment, null, /* @__PURE__ */ react_default.createElement(StyledTableCell, null, /* @__PURE__ */ react_default.createElement(
      MaybeFieldValueLink,
      {
        field,
        value,
        onFieldValueClicked,
        isField,
        isHighlighted: isValueHighlighted
      }
    ), isTagFeatureFlagOn && /* @__PURE__ */ react_default.createElement(
      MaybeTagsLink,
      {
        onTagClicked,
        field,
        tags: (_a2 = allTagsMap[tagsKey]) != null ? _a2 : []
      }
    )), haveFieldValueActions && /* @__PURE__ */ react_default.createElement(StyledTableCell, { align: "center", style: actionCellStyle }, fieldActions.length > 0 && field !== "_time" && /* @__PURE__ */ react_default.createElement(Dropdown_default, { toggle: actionToggle }, /* @__PURE__ */ react_default.createElement(Menu_default, { style: { width: 280, maxHeight: 270, overflowY: "auto" } }, fieldActions.map((Child, fieldActionsIndex) => {
      const actionKey = `field-action-${field}-${value}-${fieldActionsIndex}`;
      return /* @__PURE__ */ react_default.createElement(react_default.Fragment, { key: actionKey }, /* @__PURE__ */ react_default.createElement(
        Child,
        {
          event,
          field,
          value,
          rowIndex: index,
          pageNumber
        }
      ));
    })))));
  };
  return /* @__PURE__ */ react_default.createElement(Table_default.Row, __spreadValues({}, otherProps), /* @__PURE__ */ react_default.createElement(StyledTableCell, { colSpan: 1e3 }, /* @__PURE__ */ react_default.createElement(StyledWrapper, { "data-test": "workflow-components:RowExpander" }, eventActionComponents.length > 0 && /* @__PURE__ */ react_default.createElement(Dropdown_default, { toggle: eventActionsToggle }, /* @__PURE__ */ react_default.createElement(Menu_default, { style: { width: 150, maxHeight: 270, overflowY: "auto" } }, eventActionComponents.map((Child, eventActionsIndex) => {
    const actionKey = `event-action-${index}-${pageNumber}-${eventActionsIndex}`;
    return /* @__PURE__ */ react_default.createElement(react_default.Fragment, { key: actionKey }, /* @__PURE__ */ react_default.createElement(Child, { event, rowIndex: index, pageNumber }));
  }))), /* @__PURE__ */ react_default.createElement(Table_default, { stripeRows: false }, /* @__PURE__ */ react_default.createElement(TableHead, null, haveFieldSelection && /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { style: headCellStyle }), /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { style: headCellStyle }, /* @__PURE__ */ react_default.createElement(StyledSpan, null, (0, i18n_exports._)("Field"))), /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { style: headCellStyle }, /* @__PURE__ */ react_default.createElement(StyledSpan, null, (0, i18n_exports._)("Value"))), haveFieldValueActions && /* @__PURE__ */ react_default.createElement(Table_default.HeadCell, { align: "center", style: headCellStyle }, /* @__PURE__ */ react_default.createElement(StyledSpan, null, (0, i18n_exports._)("Actions")))), /* @__PURE__ */ react_default.createElement(Table_default.Body, null, fields.map((data) => {
    var _a2;
    const field = data;
    let fieldDropdown;
    const value = event[data];
    const rowSpan = (0, lodash_exports.isArray)(value) && value.length > 0 ? value.length : 1;
    return /* @__PURE__ */ react_default.createElement(react_exports.Fragment, { key: field }, /* @__PURE__ */ react_default.createElement(TableRow3, { key: `${field}=${value.toString()}` }, haveFieldSelection && /* @__PURE__ */ react_default.createElement(StyledTableCell, null, /* @__PURE__ */ react_default.createElement(Switch_default, { appearance: "checkbox" })), /* @__PURE__ */ react_default.createElement(StyledTableCell, { rowSpan }, fieldDropdown || maybeFieldLink(
      field,
      value.toString(),
      onFieldClicked,
      onTimeClicked,
      isField,
      timeFieldAdditionalProps,
      fieldAdditionalProps
    )), (0, lodash_exports.isArray)(value) ? getValueRow(data, (_a2 = value[0]) != null ? _a2 : "") : getValueRow(data, value)), (0, lodash_exports.isArray)(value) && value.map(
      (valueItem, i) => i > 0 && /* @__PURE__ */ react_default.createElement(TableRow3, { key: `${field}=${valueItem}` }, getValueRow(data, valueItem))
    ));
  })))), /* @__PURE__ */ react_default.createElement(
    EditTagsModal_default,
    {
      fieldName: editTagsModalData.fieldName,
      fieldValue: editTagsModalData.fieldValue,
      isOpen: editTagsModalData.isOpen,
      updateIsModalOpen,
      tags: editTagsModalData.tags,
      updateAllTags
    }
  )));
};
var RowExpander_default = RowExpander;

// esm-externals:@splunk/react-ui/Card
var Card_exports = {};
__export(Card_exports, {
  default: () => Card_default
});
var defaultImport32 = __toESM(require("@splunk/react-ui/Card"));
__reExport(Card_exports, require("@splunk/react-ui/Card"));
var Card_default = "default" in defaultImport32 ? defaultImport32.default : defaultImport32;

// esm-externals:@splunk/react-ui/Paragraph
var Paragraph_exports = {};
__export(Paragraph_exports, {
  default: () => Paragraph_default
});
var defaultImport33 = __toESM(require("@splunk/react-ui/Paragraph"));
__reExport(Paragraph_exports, require("@splunk/react-ui/Paragraph"));
var Paragraph_default = "default" in defaultImport33 ? defaultImport33.default : defaultImport33;

// src/components/Error/index.tsx
var StyledCard = styled_components_default(Card_default)`
    width: 400,
    left: 50% ,
    position: absolute,
    marginLeft: -200,
`;
var ErrorViewer = ({ error }) => {
  const errorTitle = (0, lodash_exports.isString)(error) ? (0, i18n_exports._)("Search Failure") : error.title;
  const errorMsg = (0, lodash_exports.isString)(error) ? error : error.message;
  return /* @__PURE__ */ react_default.createElement(StyledCard, null, /* @__PURE__ */ react_default.createElement(Card_default.Header, { title: errorTitle }), /* @__PURE__ */ react_default.createElement(Card_default.Body, null, /* @__PURE__ */ react_default.createElement(Paragraph_default, null, errorMsg)));
};
var Error_default = ErrorViewer;

// src/utils/DataSet.ts
var DataSet = class _DataSet {
  /**
   * @constructor
   * @param {Field[]} [fields= []] List of field name or field objects
   * @param {ColumnValue[][]} [columns=[]] List of column values related to fields
   * @returns DataSet
   */
  constructor(fields = [], columns = []) {
    __publicField(this, "fields");
    __publicField(this, "columns");
    this.fields = fields.map((field) => {
      if ((0, lodash_exports.isString)(field)) {
        return {
          name: field
        };
      }
      return field;
    });
    this.columns = columns;
  }
  /**
   * Returns a empty Dataset
   *
   * Examples:
   * ```js
   * const empty = DataSet.empty();
   * ```
   * @returns {DataSet} DataSet
   * @public
   */
  static empty() {
    return new _DataSet();
  }
  /**
   * Construct a Dataset with data in json array format
   *
   * Examples:
   * ```js
   *  const dataset = DataSet.fromJSONArray(
   *     [{ name: 'x' }, { name: 'y' }, { name: 'z' }],
   *     [{ x: 'a', y: 4, z: 70 }, { x: 'b', y: 5, z: 80 }, { x: 'c', y: 6, z: 90 }]
   *  );
   * ```
   * @param {FieldObj[]} [fields=[]] List of objects containing field names
   * @param {RowItem[]} [results=[]] List of objects containing results for each field
   * @returns {DataSet}
   * @public
   */
  static fromJSONArray(fields = [], results = []) {
    let fieldList = fields;
    if (fieldList == null || fieldList.length === 0) {
      if (results.length > 0) {
        const rowSample = results[0];
        fieldList = Object.keys(rowSample).map((field) => ({
          name: field
        }));
      } else {
        fieldList = [];
      }
    }
    const columns = fieldList.map(
      ({ name }) => results.reduce((col, row) => {
        var _a;
        col.push((_a = row[name]) != null ? _a : null);
        return col;
      }, [])
    );
    return new _DataSet(fieldList, columns);
  }
  /**
   * Construct a Dataset with data in json columns format
   *
   * Examples:
   * ```js
   *  const dataset = DataSet.fromJSONCols(
   *     [{ name: 'x' }, { name: 'y' }, { name: 'z' }],
   *     [['a', 'b', 'c'], [4, 5, 6], [70, 80, 90]];
   *  );
   * ```
   * @param {Field[]} [fields=[]] List of fields
   * @param {ColumnValue[][]} [columns=[]] list of column values
   * @returns {DataSet}
   * @public
   */
  static fromJSONCols(fields = [], columns = []) {
    return new _DataSet(fields, columns);
  }
  /**
   * Construct a Dataset with data in json rows format
   *
   * Examples:
   * ```js
   *  const dataset = DataSet.fromJSONRows(
   *     [{ name: 'x' }, { name: 'y' }, { name: 'z' }],
   *     [['a', 4, 70], ['b', 5, 80], ['c', 6, 90]];
   *  );
   * ```
   * @param {Field[]} [fields=[]] List of fields
   * @param {ColumnValue[][]} [columns=[]] list of column values
   * @returns {DataSet}
   * @public
   */
  static fromJSONRows(fields = [], rows = []) {
    return new _DataSet(fields, (0, lodash_exports.zip)(...rows));
  }
  /**
   * Convert data to json array
   * @return {JSONArray} data in json array format
   * @public
   */
  toJSONArray() {
    return {
      fields: this.fields,
      results: (0, lodash_exports.zip)(...this.columns).map(
        (row) => (0, lodash_exports.zipObject)(
          this.fields.map((field) => field.name),
          row
        )
      )
    };
  }
  /**
   * Convert data to json columns
   * @return {JSONCols} data in json columns format
   * @public
   */
  toJSONCols() {
    const { fields, columns } = this;
    return { fields, columns };
  }
  /**
   * Convert data to json rows
   * @return {JSONRows} data in json rows format
   * @public
   */
  toJSONRows() {
    return {
      fields: this.fields,
      rows: (0, lodash_exports.zip)(...this.columns)
    };
  }
  /**
   * List all fields
   * @return {FieldObj[]} fields array
   * @public
   */
  getFields() {
    return this.fields;
  }
  /**
   * List data columns
   * @return {Object} columns array
   * @public
   */
  getColumns() {
    return this.columns;
  }
  /**
   *
   * @param {String} fieldName
   * @return {ColumnValue[]} column data
   * @public
   */
  getColumnByField(fieldName) {
    const index = (0, lodash_exports.findIndex)(this.fields, ({ name }) => name === fieldName);
    return this.columns[index];
  }
  /**
   *
   * @param {String} fieldName
   * @return {Boolean}
   * @public
   */
  hasField(fieldName) {
    return (0, lodash_exports.findIndex)(this.fields, ({ name }) => name === fieldName) !== -1;
  }
  /**
   * @return {Boolean} true if DataSet has no data
   * @public
   */
  isEmpty() {
    return this.columns.length === 0;
  }
  /**
   *
   * @param {DataSet} dataSet DataSet to compare
   * @return {Boolean} true if another dataset is equals to current one
   * @public
   */
  equals(dataSet) {
    return (0, lodash_exports.isEqual)(this.fields, dataSet.fields) && (0, lodash_exports.isEqual)(this.columns, dataSet.columns);
  }
  /**
   * Returns a slice of the dataset, useful for pagination.
   * @param options {Object}
   * @param options.count {Number} number of rows
   * @param options.offset {Number} starting row index
   * @returns {DataSet}
   * @public
   */
  getPage({ count = 0, offset = 0 }) {
    const end = count <= 0 ? void 0 : offset + count;
    return _DataSet.fromJSONCols(
      this.getFields(),
      this.getColumns().map((column) => column.slice(offset, end))
    );
  }
  /**
   * Get total number of rows. Note this is not affected by the pagination.
   * @public
   */
  getTotalCount() {
    var _a, _b;
    return (_b = (_a = this.columns[0]) == null ? void 0 : _a.length) != null ? _b : 0;
  }
};

// src/utils/datasourceUtils.ts
function getDataSet(vizProps, dataSourceType = "primary") {
  var _a, _b;
  const data = (_b = (_a = vizProps.dataSources) == null ? void 0 : _a[dataSourceType]) == null ? void 0 : _b.data;
  return data ? DataSet.fromJSONCols(data.fields, data.columns) : null;
}
function getPrimaryDataSet(vizProps) {
  return getDataSet(vizProps, "primary");
}
function getRequestParams(vizProps, dataSourceType = "primary") {
  var _a, _b;
  return (_b = (_a = vizProps.dataSources) == null ? void 0 : _a[dataSourceType]) == null ? void 0 : _b.requestParams;
}
function getPrimaryRequestParams(vizProps) {
  return getRequestParams(vizProps, "primary");
}
var emptyMeta = {};
function getMeta(vizProps, dataSourceType = "primary") {
  var _a, _b, _c;
  return (_c = (_b = (_a = vizProps.dataSources) == null ? void 0 : _a[dataSourceType]) == null ? void 0 : _b.meta) != null ? _c : emptyMeta;
}
function getPrimaryMeta(vizProps) {
  return getMeta(vizProps, "primary");
}

// src/components/EventsViewer/index.tsx
var defaultOptions = {
  currentTableStyle: "list",
  showPagination: false,
  tableStyles: TableStyleSet.builtin,
  timeFormat: "lms",
  rowNumbers: false,
  wrapResults: true,
  footerFields: [],
  fieldValueHighlightMap: {}
};
var EventsViewer = ({
  dataSources,
  width = "100%",
  height = "100%",
  options = defaultOptions,
  onOptionsChange = () => {
  },
  onRequestParamsChange,
  style,
  selection,
  onTimeClicked,
  timeFieldAdditionalProps,
  onFieldClicked,
  fieldAdditionalProps,
  onFieldValueClicked,
  onTagClicked,
  isField
}) => {
  var _a, _b;
  const metaData = getPrimaryMeta({ dataSources });
  const tags = (_a = flattenTagObject(metaData == null ? void 0 : metaData.tags)) != null ? _a : {};
  const [allTagsMap, setAllTagsMap] = react_default.useState(tags);
  const updateAllTags = (0, react_exports.useCallback)((allTags) => {
    setAllTagsMap(allTags);
  }, []);
  const getExpansionRow = (event, key, index, pageNumber, ...otherProps) => /* @__PURE__ */ react_default.createElement(
    RowExpander_default,
    __spreadProps(__spreadValues({}, otherProps), {
      key: `${key}-expansion`,
      event,
      index,
      pageNumber,
      renderEventActions: options.renderEventActions,
      renderFieldActions: options.renderFieldActions,
      onFieldClicked,
      onTagClicked,
      onFieldValueClicked,
      onTimeClicked,
      isField,
      fieldValueHighlightMap: options.fieldValueHighlightMap,
      allTagsMap,
      updateAllTags,
      timeFieldAdditionalProps,
      fieldAdditionalProps
    })
  );
  const getPageToggle = (pageNumber, totalRows, selectedRows) => {
    const numberOfRowsSelected = selectedRows.filter((row) => row.pageNumber === pageNumber).length;
    if (numberOfRowsSelected === 0) {
      return "none" /* None */;
    }
    if (numberOfRowsSelected === totalRows) {
      return "all" /* All */;
    }
    return "some" /* Some */;
  };
  const styles = {
    configurationPanel: {
      padding: "6px 20px"
    }
  };
  const requestParams = getPrimaryRequestParams({ dataSources });
  if (metaData.totalCount === 0) {
    const error = {
      title: (0, i18n_exports._)("Search Results"),
      message: (0, i18n_exports._)("No Results Found.")
    };
    return /* @__PURE__ */ react_default.createElement(Error_default, { error });
  }
  const totalPages = Math.ceil(metaData.totalCount / requestParams.count) || 0;
  const page = Math.ceil(requestParams.offset / requestParams.count) + 1;
  const pagination = {
    page: page || 1,
    totalPages,
    pageLength: requestParams.count || 10,
    pageLengthOptions: options.pageLengthOptions || []
  };
  const formattingValues = (0, lodash_exports.pick)(options, options.formattingOptions);
  const renderEvents = () => {
    const updatedOptions = assign_default({}, defaultOptions, options);
    const tableStyle = options.currentTableStyle || defaultOptions.currentTableStyle;
    const tableStyleDefinition = updatedOptions.tableStyles.get(tableStyle);
    if (!tableStyleDefinition) {
      throw new Error(`No table style definition found for currentTableStyle: ${tableStyle}`);
    }
    const eventsData = getPrimaryDataSet({ dataSources });
    const TableComponent = tableStyleDefinition.component;
    const eventsDataArray = eventsData.toJSONArray();
    const updatedSelection = selection ? __spreadProps(__spreadValues({}, selection), {
      pageToggle: getPageToggle(page, eventsDataArray.results.length, selection.rows)
    }) : void 0;
    return /* @__PURE__ */ react_default.createElement(
      TableComponent,
      {
        fields: eventsDataArray.fields,
        events: eventsDataArray.results,
        timeFormat: options.timeFormat,
        getExpansionRow,
        rowNumbers: options.rowNumbers,
        wrapResults: options.wrapResults,
        pageNumber: page,
        selection: updatedSelection,
        onTimeClicked,
        timeFieldAdditionalProps,
        onFieldValueClicked,
        onTagClicked,
        isField,
        footerFields: options.footerFields,
        fieldValueHighlightMap: options.fieldValueHighlightMap,
        allTagsMap,
        updateAllTags
      }
    );
  };
  const selectionActions = selection == null ? void 0 : selection.actions;
  const onActionClicked = selection == null ? void 0 : selection.onActionClicked;
  const selectionCount = ((_b = selection == null ? void 0 : selection.rows) == null ? void 0 : _b.length) || 0;
  return /* @__PURE__ */ react_default.createElement(
    "div",
    {
      "data-test": "workflow-components:EventsViewer",
      style: __spreadValues({
        height,
        width,
        overflowY: "auto"
      }, style)
    },
    /* @__PURE__ */ react_default.createElement(
      ConfigurationPanel_default,
      {
        requestParams,
        tableStyles: options.tableStyles,
        currentTableStyle: options.currentTableStyle,
        formattingOptions: options.formattingOptions,
        onOptionsChange,
        showPagination: options.showPagination,
        pagination,
        style: styles.configurationPanel,
        onRequestParamsChange,
        formattingValues,
        selectionActions,
        onSelectionActionClicked: onActionClicked,
        selectionCount
      }
    ),
    renderEvents()
  );
};
var EventsViewer_default = EventsViewer;
//# sourceMappingURL=index.js.map
