"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.cloneLayer = void 0; exports.fieldIsInvalid = fieldIsInvalid; exports.getFiltersInLayer = getFiltersInLayer; exports.getNotifiableFeatures = getNotifiableFeatures; exports.getPrecisionErrorWarningMessages = getPrecisionErrorWarningMessages; exports.getSamplingValue = getSamplingValue; exports.getShardFailuresWarningMessages = getShardFailuresWarningMessages; exports.getUnsupportedOperationsWarningMessage = getUnsupportedOperationsWarningMessage; exports.getVisualDefaultsForLayer = getVisualDefaultsForLayer; exports.isColumnInvalid = isColumnInvalid; exports.isSamplingValueEnabled = isSamplingValueEnabled; var _react = _interopRequireDefault(require("react")); var _i18n = require("@kbn/i18n"); var _i18nReact = require("@kbn/i18n-react"); var _eui = require("@elastic/eui"); var _lodash = require("lodash"); var _public = require("@kbn/data-plugin/public"); var _visualizationUiComponents = require("@kbn/visualization-ui-components"); var _utils = require("../../utils"); var _operations = require("./operations"); var _helpers = require("./operations/definitions/helpers"); var _pure_utils = require("./pure_utils"); var _state_helpers = require("./state_helpers"); var _terms = require("./operations/definitions/terms"); var _constants = require("./operations/definitions/terms/constants"); var _transpose_helpers = require("../../../common/expressions/datatable/transpose_helpers"); var _info_badges = require("./info_badges"); var _ignore_global_filter = require("../../shared_components/ignore_global_filter"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ function isMinOrMaxColumn(column) { if (!column) { return false; } return (0, _helpers.isColumnOfType)('max', column) || (0, _helpers.isColumnOfType)('min', column); } function isReferenceColumn(column) { return 'references' in column; } function isSamplingValueEnabled(layer) { // Do not use columnOrder here as it needs to check also inside formulas columns return !Object.values(layer.columns).some(column => isMinOrMaxColumn(column) || isReferenceColumn(column) && isMinOrMaxColumn(layer.columns[column.references[0]])); } /** * Centralized logic to get the actual random sampling value for a layer * @param layer * @returns */ function getSamplingValue(layer) { var _layer$sampling; return isSamplingValueEnabled(layer) ? (_layer$sampling = layer.sampling) !== null && _layer$sampling !== void 0 ? _layer$sampling : 1 : 1; } function isColumnInvalid(layer, columnId, indexPattern, dateRange, targetBars) { var _operationDefinition$; const column = layer.columns[columnId]; if (!column || !indexPattern) return; const operationDefinition = column.operationType && _operations.operationDefinitionMap[column.operationType]; // check also references for errors const referencesHaveErrors = true && 'references' in column && Boolean(getReferencesErrors(layer, column, indexPattern, dateRange, targetBars).filter(Boolean).length); const operationErrorMessages = operationDefinition && ((_operationDefinition$ = operationDefinition.getErrorMessage) === null || _operationDefinition$ === void 0 ? void 0 : _operationDefinition$.call(operationDefinition, layer, columnId, indexPattern, dateRange, _operations.operationDefinitionMap, targetBars)); // it looks like this is just a back-stop since we prevent // invalid filters from being set at the UI level const filterHasError = column.filter ? !(0, _visualizationUiComponents.isQueryValid)(column.filter, indexPattern) : false; return operationErrorMessages && operationErrorMessages.length > 0 || referencesHaveErrors || filterHasError; } function getReferencesErrors(layer, column, indexPattern, dateRange, targetBars) { var _column$references; return (_column$references = column.references) === null || _column$references === void 0 ? void 0 : _column$references.map(referenceId => { var _layer$columns$refere, _referencedDefinition; const referencedOperation = (_layer$columns$refere = layer.columns[referenceId]) === null || _layer$columns$refere === void 0 ? void 0 : _layer$columns$refere.operationType; const referencedDefinition = _operations.operationDefinitionMap[referencedOperation]; return referencedDefinition === null || referencedDefinition === void 0 ? void 0 : (_referencedDefinition = referencedDefinition.getErrorMessage) === null || _referencedDefinition === void 0 ? void 0 : _referencedDefinition.call(referencedDefinition, layer, referenceId, indexPattern, dateRange, _operations.operationDefinitionMap, targetBars); }); } function fieldIsInvalid(layer, columnId, indexPattern) { var _getInvalidFieldMessa; const column = layer.columns[columnId]; if (!column || !(0, _pure_utils.hasField)(column)) { return false; } return !!((_getInvalidFieldMessa = (0, _helpers.getInvalidFieldMessage)(layer, columnId, indexPattern)) !== null && _getInvalidFieldMessa !== void 0 && _getInvalidFieldMessa.length); } const accuracyModeDisabledWarning = (columnName, columnId, enableAccuracyMode) => ({ severity: 'warning', displayLocations: [{ id: 'toolbar' }, { id: 'dimensionButton', dimensionId: columnId }], fixableInEditor: true, shortMessage: _i18n.i18n.translate('xpack.lens.indexPattern.precisionErrorWarning.accuracyDisabled.shortMessage', { defaultMessage: 'This might be an approximation. For more precise results, you can enable accuracy mode, but it increases the load on the Elasticsearch cluster.' }), longMessage: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.precisionErrorWarning.accuracyDisabled", defaultMessage: "{name} might be an approximation. You can enable accuracy mode for more precise results, but note that it increases the load on the Elasticsearch cluster.", values: { name: /*#__PURE__*/_react.default.createElement("strong", null, columnName) } }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, { size: "s" }), /*#__PURE__*/_react.default.createElement(_eui.EuiLink, { "data-test-subj": "lnsPrecisionWarningEnableAccuracy", onClick: enableAccuracyMode }, _i18n.i18n.translate('xpack.lens.indexPattern.enableAccuracyMode', { defaultMessage: 'Enable accuracy mode' }))) }); const accuracyModeEnabledWarning = (columnName, columnId, docLink) => ({ severity: 'warning', displayLocations: [{ id: 'toolbar' }, { id: 'dimensionButton', dimensionId: columnId }], fixableInEditor: true, shortMessage: _i18n.i18n.translate('xpack.lens.indexPattern.precisionErrorWarning.accuracyEnabled.shortMessage', { defaultMessage: 'This might be an approximation. For more precise results, use Filters or increase the number of Top Values.' }), longMessage: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.precisionErrorWarning.accuracyEnabled", defaultMessage: "{name} might be an approximation. For more precise results, try increasing the number of {topValues} or using {filters} instead. {learnMoreLink}", values: { name: /*#__PURE__*/_react.default.createElement("strong", null, columnName), topValues: /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.precisionErrorWarning.topValues", defaultMessage: "Top Values" })), filters: /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.precisionErrorWarning.filters", defaultMessage: "Filters" })), learnMoreLink: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, { href: docLink, target: "_blank", external: true }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { defaultMessage: "Learn more.", id: "xpack.lens.indexPattern.precisionErrorWarning.link" })) } }) }); function getShardFailuresWarningMessages(state, warning, request, response, theme) { if (state) { if (warning.type === 'shard_failure') { switch (warning.reason.type) { case 'unsupported_aggregation_on_downsampled_index': return Object.values(state.layers).flatMap(layer => (0, _lodash.uniq)(Object.values(layer.columns).filter(col => ['median', 'percentile', 'percentile_rank', 'last_value', 'unique_count', 'standard_deviation'].includes(col.operationType)).map(col => col.label)).map(label => ({ uniqueId: `unsupported_aggregation_on_downsampled_index--${label}`, severity: 'warning', fixableInEditor: true, displayLocations: [{ id: 'toolbar' }, { id: 'embeddableBadge' }], shortMessage: '', longMessage: _i18n.i18n.translate('xpack.lens.indexPattern.tsdbRollupWarning', { defaultMessage: '{label} uses a function that is unsupported by rolled up data. Select a different function or change the time range.', values: { label } }) }))); default: return [{ uniqueId: `shard_failure`, severity: 'warning', fixableInEditor: true, displayLocations: [{ id: 'toolbar' }, { id: 'embeddableBadge' }], shortMessage: '', longMessage: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, { size: "s" }, /*#__PURE__*/_react.default.createElement("strong", null, warning.message), /*#__PURE__*/_react.default.createElement("p", null, warning.text)), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, { size: "s" }), warning.text ? /*#__PURE__*/_react.default.createElement(_public.ShardFailureOpenModalButton, { theme: theme, title: warning.message, size: "m", getRequestMeta: () => ({ request: request, response }), color: "primary", isButtonEmpty: true }) : null) }]; } } } return []; } function getUnsupportedOperationsWarningMessage(state, { dataViews }, docLinks) { const warningMessages = []; const columnsWithUnsupportedOperations = Object.values(state.layers) // filter layers without dataView loaded yet .filter(({ indexPatternId }) => dataViews.indexPatterns[indexPatternId]).flatMap(layer => { const dataView = dataViews.indexPatterns[layer.indexPatternId]; const columnsEntries = Object.entries(layer.columns); return columnsEntries.filter(([_, column]) => { if (!(0, _pure_utils.hasField)(column)) { return false; } const field = dataView.getFieldByName(column.sourceField); if (!field) { return false; } return !_operations.operationDefinitionMap[column.operationType].getPossibleOperationForField(field) && (field === null || field === void 0 ? void 0 : field.timeSeriesMetric) === 'counter'; }).map(([id, fieldColumn]) => [fieldColumn, layer.columns[(0, _operations.getReferenceRoot)(layer, id)]]); }); if (columnsWithUnsupportedOperations.length) { // group the columns by field // then group together columns of a formula/referenced operation who use the same field const columnsGroupedByField = Object.values((0, _lodash.groupBy)(columnsWithUnsupportedOperations, ([column]) => column.sourceField)).map(columnsList => (0, _lodash.uniqBy)(columnsList, ([column, rootColumn]) => rootColumn !== null && rootColumn !== void 0 ? rootColumn : column)); for (const columnsGrouped of columnsGroupedByField) { const sourceField = columnsGrouped[0][0].sourceField; warningMessages.push({ severity: 'warning', fixableInEditor: false, displayLocations: [{ id: 'toolbar' }, { id: 'embeddableBadge' }], shortMessage: _i18n.i18n.translate('xpack.lens.indexPattern.tsdbErrorWarning.unsupportedCounterOperationErrorWarning.shortMessage', { defaultMessage: 'The result of {count} {count, plural, one {operation} other {operations}} might be meaningless for {field}: {operations}', values: { count: columnsGrouped.length, operations: columnsGrouped.map(([affectedColumn, rootColumn]) => (rootColumn !== null && rootColumn !== void 0 ? rootColumn : affectedColumn).label).join(', '), field: sourceField } }), longMessage: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.unsupportedCounterOperationErrorWarning", defaultMessage: "While {count} {count, plural, one {operation} other {operations}} for {field} {count, plural, one {is} other {are}} allowed the result might be meaningless: {operations}. To learn more about this, {link}.", values: { count: columnsGrouped.length, operations: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, columnsGrouped.map(([affectedColumn, rootColumn], i) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, { key: (rootColumn !== null && rootColumn !== void 0 ? rootColumn : affectedColumn).label }, /*#__PURE__*/_react.default.createElement("strong", null, (rootColumn !== null && rootColumn !== void 0 ? rootColumn : affectedColumn).label), i < columnsGrouped.length - 1 ? ', ' : ''))), field: sourceField, link: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, { href: docLinks.links.fleet.datastreamsTSDSMetrics, target: "_blank", external: true }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { defaultMessage: "visit the Time series documentation", id: "xpack.lens.indexPattern.unsupportedCounterOperationErrorWarning.link" })) } })) }); } } return warningMessages; } function getPrecisionErrorWarningMessages(datatableUtilities, state, { activeData, dataViews }, docLinks, setState) { const warningMessages = []; if (state && activeData) { Object.entries(activeData).reduce((acc, [layerId, { columns }]) => { acc.push(...columns.map(column => ({ layerId, column }))); return acc; }, []).forEach(({ layerId, column }) => { const currentLayer = state.layers[layerId]; const currentColumn = currentLayer === null || currentLayer === void 0 ? void 0 : currentLayer.columns[column.id]; if (currentLayer && currentColumn && datatableUtilities.hasPrecisionError(column)) { const indexPattern = dataViews.indexPatterns[currentLayer.indexPatternId]; if (!indexPattern) { return; } // currentColumnIsTerms is mostly a type guard. If there's a precision error, // we already know that we're dealing with a terms-based operation (at least for now). const currentColumnIsTerms = (0, _helpers.isColumnOfType)('terms', currentColumn); const isAscendingCountSorting = currentColumnIsTerms && currentColumn.params.orderBy.type === 'column' && currentColumn.params.orderDirection === 'asc' && (0, _helpers.isColumnOfType)('count', currentLayer.columns[currentColumn.params.orderBy.columnId]); const usesFloatingPointField = currentColumnIsTerms && !(0, _terms.supportsRarityRanking)(indexPattern.getFieldByName(currentColumn.sourceField)); const usesMultipleFields = currentColumnIsTerms && (currentColumn.params.secondaryFields || []).length > 0; if (currentColumnIsTerms && (!isAscendingCountSorting || usesFloatingPointField || usesMultipleFields)) { warningMessages.push(currentColumn.params.accuracyMode ? accuracyModeEnabledWarning(column.name, column.id, docLinks.links.aggs.terms_doc_count_error) : accuracyModeDisabledWarning(column.name, column.id, () => { setState(prevState => (0, _state_helpers.mergeLayer)({ state: prevState, layerId, newLayer: (0, _operations.updateDefaultLabels)((0, _operations.updateColumnParam)({ layer: currentLayer, columnId: column.id, paramName: 'accuracyMode', value: true }), indexPattern) })); })); } else { warningMessages.push({ severity: 'warning', displayLocations: [{ id: 'toolbar' }, { id: 'dimensionButton', dimensionId: column.id }], shortMessage: _i18n.i18n.translate('xpack.lens.indexPattern.precisionErrorWarning.ascendingCountPrecisionErrorWarning.shortMessage', { defaultMessage: 'This may be approximate depending on how the data is indexed. For more precise results, sort by rarity.' }), longMessage: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { id: "xpack.lens.indexPattern.ascendingCountPrecisionErrorWarning", defaultMessage: "{name} for this visualization may be approximate due to how the data is indexed. Try sorting by rarity instead of ascending count of records. To learn more about this limit, {link}.", values: { name: /*#__PURE__*/_react.default.createElement("strong", null, column.name), link: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, { href: docLinks.links.aggs.rare_terms, target: "_blank", external: true }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, { defaultMessage: "visit the documentation", id: "xpack.lens.indexPattern.ascendingCountPrecisionErrorWarning.link" })) } }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, { size: "s" }), /*#__PURE__*/_react.default.createElement(_eui.EuiLink, { onClick: () => { setState(prevState => (0, _state_helpers.mergeLayer)({ state: prevState, layerId, newLayer: (0, _operations.updateDefaultLabels)((0, _operations.updateColumnParam)({ layer: currentLayer, columnId: column.id, paramName: 'orderBy', value: { type: 'rare', maxDocCount: _constants.DEFAULT_MAX_DOC_COUNT } }), indexPattern) })); } }, _i18n.i18n.translate('xpack.lens.indexPattern.switchToRare', { defaultMessage: 'Rank by rarity' }))), fixableInEditor: true }); } } }); } return warningMessages; } function getVisualDefaultsForLayer(layer) { return Object.keys(layer.columns).reduce((memo, columnId) => { const column = layer.columns[columnId]; if (column !== null && column !== void 0 && column.operationType) { var _opDefinition$getDefa; const opDefinition = _operations.operationDefinitionMap[column.operationType]; const params = (_opDefinition$getDefa = opDefinition.getDefaultVisualSettings) === null || _opDefinition$getDefa === void 0 ? void 0 : _opDefinition$getDefa.call(opDefinition, column); if (params) { memo[columnId] = params; } } return memo; }, {}); } function getNotifiableFeatures(state, frame, visualizationInfo) { if (!visualizationInfo) { return []; } const features = []; const layers = Object.entries(state.layers); const layersWithCustomSamplingValues = layers.filter(([, layer]) => getSamplingValue(layer) !== 1); if (layersWithCustomSamplingValues.length) { features.push({ uniqueId: 'random_sampling_info', severity: 'info', fixableInEditor: false, shortMessage: _i18n.i18n.translate('xpack.lens.indexPattern.samplingPerLayer', { defaultMessage: 'Sampling probability by layer' }), longMessage: /*#__PURE__*/_react.default.createElement(_info_badges.ReducedSamplingSectionEntries, { layers: layersWithCustomSamplingValues, dataViews: frame.dataViews, visualizationInfo: visualizationInfo }), displayLocations: [{ id: 'embeddableBadge' }] }); } const layersWithIgnoreGlobalFilters = layers.filter(([, layer]) => layer.ignoreGlobalFilters); if (layersWithIgnoreGlobalFilters.length) { features.push({ uniqueId: 'ignoring-global-filters-layers', severity: 'info', fixableInEditor: false, shortMessage: _i18n.i18n.translate('xpack.lens.xyChart.layerAnnotationsIgnoreTitle', { defaultMessage: 'Layers ignoring global filters' }), longMessage: /*#__PURE__*/_react.default.createElement(_ignore_global_filter.IgnoredGlobalFiltersEntries, { layers: layersWithIgnoreGlobalFilters.map(([layerId, { indexPatternId }]) => ({ layerId, indexPatternId })), visualizationInfo: visualizationInfo, dataViews: frame.dataViews }), displayLocations: [{ id: 'embeddableBadge' }] }); } return features; } /** * Some utilities to extract queries/filters from specific column types */ /** * Given a Filters column, extract and filter useful queries from it */ function extractQueriesFromFilters(queries) { return queries === null || queries === void 0 ? void 0 : queries.map(({ input }) => input).filter(({ query }) => (query === null || query === void 0 ? void 0 : query.trim()) && query !== '*'); } /** * Given an Interval column in range mode transform the ranges into KQL queries */ function extractQueriesFromRanges(column) { return column.params.ranges.map(({ from, to }) => { let rangeQuery = ''; if (from != null && isFinite(from)) { rangeQuery += `${column.sourceField} >= ${from}`; } if (to != null && isFinite(to)) { if (rangeQuery.length) { rangeQuery += ' AND '; } rangeQuery += `${column.sourceField} <= ${to}`; } return { query: rangeQuery, language: 'kuery' }; }).filter(({ query }) => query === null || query === void 0 ? void 0 : query.trim()); } /** * If the data view doesn't have a default time field, Discover can't use the global time range - construct an equivalent filter instead */ function extractTimeRangeFromDateHistogram(column, timeRange) { return [{ language: 'kuery', query: `"${column.sourceField}" >= "${timeRange.from}" AND "${column.sourceField}" <= "${timeRange.to}"` }]; } /** * Given an Terms/Top values column transform each entry into a "field: term" KQL query * This works also for multi-terms variant */ function extractQueriesFromTerms(column, colId, data) { const fields = [column.sourceField].concat(column.params.secondaryFields || []).filter(Boolean); // extract the filters from the columns of the activeData const queries = data.rows.map(({ [colId]: value }) => { if (value == null) { return; } if (typeof value !== 'string' && Array.isArray(value.keys)) { return value.keys.map((term, index) => `${fields[index]}: ${`"${term === '' ? (0, _lodash.escape)(term) : term}"`}`).join(' AND '); } return `${column.sourceField}: ${`"${value === '' ? (0, _lodash.escape)(value) : value}"`}`; }).filter(Boolean); // dedup queries before returning return [...new Set(queries)].map(query => ({ language: 'kuery', query })); } /** * Used for a Terms column to decide whether to use a simple existence query (fallback) instead * of more specific queries. * The check targets the scenarios where no data is available, or when there's a transposed table * and it's not yet possible to track it back to the original table */ function shouldUseTermsFallback(data, colId) { var _data$columns$find; const dataId = data === null || data === void 0 ? void 0 : (_data$columns$find = data.columns.find(({ id }) => (0, _transpose_helpers.getOriginalId)(id) === colId)) === null || _data$columns$find === void 0 ? void 0 : _data$columns$find.id; return !dataId || dataId !== colId; } /** * Collect filters from metrics: * * if there's at least one unfiltered metric, then just return an empty list of filters * * otherwise get all the filters, with the only exception of those from formula (referenced columns will have it anyway) */ function collectFiltersFromMetrics(layer, columnIds) { // Isolate filtered metrics first // mind to ignore non-filterable columns and formula columns const metricColumns = Object.keys(layer.columns).filter(colId => { const column = layer.columns[colId]; const operationDefinition = _operations.operationDefinitionMap[column === null || column === void 0 ? void 0 : column.operationType]; return !(column !== null && column !== void 0 && column.isBucketed) && // global filters for formulas are picked up by referenced columns !(0, _helpers.isColumnOfType)('formula', column) && (operationDefinition === null || operationDefinition === void 0 ? void 0 : operationDefinition.filterable); }); const { filtered = [], unfiltered = [] } = (0, _lodash.groupBy)(metricColumns, colId => { var _layer$columns$colId; return (_layer$columns$colId = layer.columns[colId]) !== null && _layer$columns$colId !== void 0 && _layer$columns$colId.filter ? 'filtered' : 'unfiltered'; }); const filteredMetrics = filtered.map(colId => { var _layer$columns$colId2; return (_layer$columns$colId2 = layer.columns[colId]) === null || _layer$columns$colId2 === void 0 ? void 0 : _layer$columns$colId2.filter; }) // filter out empty filters as well .filter(filter => { var _filter$query; return filter === null || filter === void 0 ? void 0 : (_filter$query = filter.query) === null || _filter$query === void 0 ? void 0 : _filter$query.trim(); }); return { enabled: unfiltered.length ? [] : filteredMetrics, disabled: unfiltered.length ? filteredMetrics : [] }; } function collectOnlyValidQueries(filteredQueries, operationQueries, queryLanguage) { return [filteredQueries[queryLanguage], ...operationQueries.map(({ [queryLanguage]: filter }) => filter)].filter(filters => filters === null || filters === void 0 ? void 0 : filters.length); } function getFiltersInLayer(layer, columnIds, layerData, indexPattern, timeRange) { const filtersGroupedByState = collectFiltersFromMetrics(layer, columnIds); const [enabledFiltersFromMetricsByLanguage, disabledFitleredFromMetricsByLanguage] = ['enabled', 'disabled'].map(state => (0, _lodash.groupBy)(filtersGroupedByState[state], 'language')); const filterOperationsOrErrors = columnIds.map(colId => { const column = layer.columns[colId]; if ((0, _helpers.isColumnOfType)('filters', column)) { const groupsByLanguage = (0, _lodash.groupBy)(column.params.filters, ({ input }) => input.language); return { kuery: extractQueriesFromFilters(groupsByLanguage.kuery), lucene: extractQueriesFromFilters(groupsByLanguage.lucene) }; } if ((0, _helpers.isColumnOfType)('range', column) && column.sourceField) { return { kuery: extractQueriesFromRanges(column) }; } if ((0, _helpers.isColumnOfType)('date_histogram', column) && timeRange && column.sourceField && !column.params.ignoreTimeRange && indexPattern.timeFieldName !== column.sourceField) { if (indexPattern.timeFieldName) { // non-default time field is not supported in Discover if data view has a time field return { error: _i18n.i18n.translate('xpack.lens.indexPattern.nonDefaultTimeFieldError', { defaultMessage: '"Explore data in Discover" does not support date histograms on non-default time fields if time field is set on the data view' }) }; } // if the data view has no default time field but the date histograms' time field is bound to the time range, create a KQL query for the time range return { kuery: extractTimeRangeFromDateHistogram(column, timeRange) }; } if ((0, _helpers.isColumnOfType)('terms', column) && !(column.params.otherBucket || column.params.missingBucket)) { if (!layerData || shouldUseTermsFallback(layerData, colId)) { const fields = _operations.operationDefinitionMap[column.operationType].getCurrentFields(column); return { kuery: fields.map(field => ({ query: `"${field}": *`, language: 'kuery' })) }; } return { kuery: extractQueriesFromTerms(column, colId, layerData) }; } }).filter(Boolean); const errors = filterOperationsOrErrors.filter(filter => filter && 'error' in filter); if (errors.length) { return { error: errors.map(({ error }) => error).join(', ') }; } const filterOperations = filterOperationsOrErrors; return { enabled: { kuery: collectOnlyValidQueries(enabledFiltersFromMetricsByLanguage, filterOperations, 'kuery'), lucene: collectOnlyValidQueries(enabledFiltersFromMetricsByLanguage, filterOperations, 'lucene') }, disabled: { kuery: [disabledFitleredFromMetricsByLanguage.kuery || []].filter(filter => filter.length), lucene: [disabledFitleredFromMetricsByLanguage.lucene || []].filter(filter => filter.length) } }; } const cloneLayer = (layers, layerId, newLayerId, getNewId) => { if (layers[layerId]) { var _layers$layerId$colum, _layers$layerId; return { ...layers, [newLayerId]: (0, _utils.renewIDs)(layers[layerId], Object.keys((_layers$layerId$colum = (_layers$layerId = layers[layerId]) === null || _layers$layerId === void 0 ? void 0 : _layers$layerId.columns) !== null && _layers$layerId$colum !== void 0 ? _layers$layerId$colum : {}), getNewId) }; } return layers; }; exports.cloneLayer = cloneLayer;