"use strict";
(globalThis["__googlesitekit_webpackJsonp"] = globalThis["__googlesitekit_webpackJsonp"] || []).push([["googlesitekit-datastore-user"],{

/***/ "./js/components/ChangeArrow.js":
/*!**************************************!*\
  !*** ./js/components/ChangeArrow.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ "../node_modules/prop-types/index.js");
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! classnames */ "../node_modules/classnames/index.js");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react/jsx-runtime */ "../node_modules/react/jsx-runtime.js");
/**
 * External dependencies
 */



function ChangeArrow({
  direction,
  invertColor,
  width,
  height
}) {
  return /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_1__.jsx)("svg", {
    className: classnames__WEBPACK_IMPORTED_MODULE_0___default()('googlesitekit-change-arrow', `googlesitekit-change-arrow--${direction}`, {
      'googlesitekit-change-arrow--inverted-color': invertColor
    }),
    width: width,
    height: height,
    viewBox: "0 0 10 10",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    children: /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_1__.jsx)("path", {
      d: "M5.625 10L5.625 2.375L9.125 5.875L10 5L5 -1.76555e-07L-2.7055e-07 5L0.875 5.875L4.375 2.375L4.375 10L5.625 10Z",
      fill: "currentColor"
    })
  });
}
ChangeArrow.propTypes = {
  direction: (prop_types__WEBPACK_IMPORTED_MODULE_2___default().string),
  invertColor: (prop_types__WEBPACK_IMPORTED_MODULE_2___default().bool),
  width: (prop_types__WEBPACK_IMPORTED_MODULE_2___default().number),
  height: (prop_types__WEBPACK_IMPORTED_MODULE_2___default().number)
};
ChangeArrow.defaultProps = {
  direction: 'up',
  invertColor: false,
  width: 9,
  height: 9
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ChangeArrow);

/***/ }),

/***/ "./js/components/KeyMetrics/constants.js":
/*!***********************************************!*\
  !*** ./js/components/KeyMetrics/constants.js ***!
  \***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EFFECTIVE_SELECTION: () => (/* binding */ EFFECTIVE_SELECTION),
/* harmony export */   KEY_METRICS_GROUP_CONTENT_PERFORMANCE: () => (/* binding */ KEY_METRICS_GROUP_CONTENT_PERFORMANCE),
/* harmony export */   KEY_METRICS_GROUP_CURRENT: () => (/* binding */ KEY_METRICS_GROUP_CURRENT),
/* harmony export */   KEY_METRICS_GROUP_DRIVING_TRAFFIC: () => (/* binding */ KEY_METRICS_GROUP_DRIVING_TRAFFIC),
/* harmony export */   KEY_METRICS_GROUP_GENERATING_LEADS: () => (/* binding */ KEY_METRICS_GROUP_GENERATING_LEADS),
/* harmony export */   KEY_METRICS_GROUP_SELLING_PRODUCTS: () => (/* binding */ KEY_METRICS_GROUP_SELLING_PRODUCTS),
/* harmony export */   KEY_METRICS_GROUP_SUGGESTED: () => (/* binding */ KEY_METRICS_GROUP_SUGGESTED),
/* harmony export */   KEY_METRICS_GROUP_VISITORS: () => (/* binding */ KEY_METRICS_GROUP_VISITORS),
/* harmony export */   KEY_METRICS_SELECTED: () => (/* binding */ KEY_METRICS_SELECTED),
/* harmony export */   KEY_METRICS_SELECTION_FORM: () => (/* binding */ KEY_METRICS_SELECTION_FORM),
/* harmony export */   KEY_METRICS_SELECTION_PANEL_OPENED_KEY: () => (/* binding */ KEY_METRICS_SELECTION_PANEL_OPENED_KEY),
/* harmony export */   KEY_METRICS_SETUP_CTA_WIDGET_SLUG: () => (/* binding */ KEY_METRICS_SETUP_CTA_WIDGET_SLUG),
/* harmony export */   MAX_SELECTED_METRICS_COUNT: () => (/* binding */ MAX_SELECTED_METRICS_COUNT),
/* harmony export */   MIN_SELECTED_METRICS_COUNT: () => (/* binding */ MIN_SELECTED_METRICS_COUNT),
/* harmony export */   UNSTAGED_SELECTION: () => (/* binding */ UNSTAGED_SELECTION)
/* harmony export */ });
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n");
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__);
/**
 * Key Metrics components - constants.
 *
 * Site Kit by Google, Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */

const KEY_METRICS_SETUP_CTA_WIDGET_SLUG = 'key-metrics-setup-cta-widget';
const KEY_METRICS_SELECTION_PANEL_OPENED_KEY = 'googlesitekit-key-metrics-selection-panel-opened';
const KEY_METRICS_SELECTION_FORM = 'key-metrics-selection-form';
const KEY_METRICS_SELECTED = 'key-metrics-selected';
const EFFECTIVE_SELECTION = 'key-metrics-effective-selection';
const UNSTAGED_SELECTION = 'key-metrics-unstaged-selection';
const MIN_SELECTED_METRICS_COUNT = 2;
const MAX_SELECTED_METRICS_COUNT = 8;
const KEY_METRICS_GROUP_CURRENT = {
  SLUG: 'current-selection',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Current selection', 'google-site-kit')
};
const KEY_METRICS_GROUP_SUGGESTED = {
  SLUG: 'suggested',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Suggested', 'google-site-kit')
};
const KEY_METRICS_GROUP_VISITORS = {
  SLUG: 'visitors',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Visitors', 'google-site-kit')
};
const KEY_METRICS_GROUP_DRIVING_TRAFFIC = {
  SLUG: 'driving-traffic',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Driving traffic', 'google-site-kit')
};
const KEY_METRICS_GROUP_GENERATING_LEADS = {
  SLUG: 'generating-leads',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Generating leads', 'google-site-kit')
};
const KEY_METRICS_GROUP_SELLING_PRODUCTS = {
  SLUG: 'selling-products',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Selling products', 'google-site-kit')
};
const KEY_METRICS_GROUP_CONTENT_PERFORMANCE = {
  SLUG: 'content-performance',
  LABEL: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Content performance', 'google-site-kit')
};

/***/ }),

/***/ "./js/components/KeyMetrics/key-metrics-widgets.js":
/*!*********************************************************!*\
  !*** ./js/components/KeyMetrics/key-metrics-widgets.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   KEY_METRICS_WIDGETS: () => (/* binding */ KEY_METRICS_WIDGETS)
/* harmony export */ });
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n");
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/js/googlesitekit/datastore/user/constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/js/googlesitekit/datastore/site/constants */ "./js/googlesitekit/datastore/site/constants.js");
/* harmony import */ var _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/modules/analytics-4/datastore/constants */ "./js/modules/analytics-4/datastore/constants.js");
/* harmony import */ var _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./shouldDisplayWidgetWithConversionEvent */ "./js/components/KeyMetrics/shouldDisplayWidgetWithConversionEvent.js");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants */ "./js/components/KeyMetrics/constants.js");
/**
 * Key Metrics widgets metadata.
 *
 * Site Kit by Google, Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */


/**
 * Internal dependencies
 */






/**
 * Determines whether to show a widget the requires Analytics 4 and AdSense to be linked.
 *
 * For admin dashboards, the widget will be shown if both modules are activate so that
 * the connection CTA can be shown if they have not been linked.
 *
 * For view-only dashboards, the widget will only be displayed if both modules are linked.
 *
 * @since 1.121.0
 *
 * @param {Object}   options                     Options object.
 * @param {Function} options.select              Data store select function.
 * @param {boolean}  options.isViewOnlyDashboard Whether the current dashboard is view only.
 * @return {boolean} Whether to display the widget.
 */
function shouldDisplayWidgetWithAnalytics4AndAdSenseLinked({
  select,
  isViewOnlyDashboard
}) {
  if (!isViewOnlyDashboard) {
    return true;
  }
  if (isViewOnlyDashboard && select(_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.MODULES_ANALYTICS_4).getAdSenseLinked()) {
    return true;
  }
  return false;
}

/**
 * Determines whether to display a widget that requires custom dimensions in the key
 * metrics selection panel.
 *
 * All widgets are displayed in authenticated dashboard. However, in view only dashboard,
 * widgets that require custom dimensions will only be displayed if the required custom
 * dimensions are available in the shared property.
 *
 * This function is attached to the widget object that requires the custom dimensions and
 * has the `requiredCustomDimensions` property.
 *
 * @since 1.113.0
 *
 * @param {Object}   options                     Options object.
 * @param {Function} options.select              Data store select function.
 * @param {boolean}  options.isViewOnlyDashboard Whether the current dashboard is view only.
 * @return {boolean} Whether to display the widget.
 */
function shouldDisplayWidgetWithCustomDimensions({
  select,
  isViewOnlyDashboard
}) {
  if (!isViewOnlyDashboard) {
    return true;
  }
  return select(_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.MODULES_ANALYTICS_4).hasCustomDimensions(
  // This property is available to the widget object that requires the
  // custom dimensions, where the function is attached.
  this.requiredCustomDimensions);
}
const KEY_METRICS_WIDGETS = {
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top earning pages', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages that generated the most AdSense revenue', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages that generated the most AdSense revenue', 'google-site-kit'),
    displayInSelectionPanel: shouldDisplayWidgetWithAnalytics4AndAdSenseLinked,
    displayInList: shouldDisplayWidgetWithAnalytics4AndAdSenseLinked,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top recent trending pages', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages with the most pageviews published in the last 3 days', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages with the most pageviews published in the last 3 days', 'google-site-kit'),
    requiredCustomDimensions: ['googlesitekit_post_date'],
    displayInSelectionPanel: shouldDisplayWidgetWithCustomDimensions,
    displayInWidgetArea: shouldDisplayWidgetWithCustomDimensions,
    displayInList: shouldDisplayWidgetWithCustomDimensions,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_POPULAR_AUTHORS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Most popular authors by pageviews', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Authors whose posts got the most visits', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Authors whose posts got the most visits', 'google-site-kit'),
    requiredCustomDimensions: ['googlesitekit_post_author'],
    displayInSelectionPanel: shouldDisplayWidgetWithCustomDimensions,
    displayInWidgetArea: shouldDisplayWidgetWithCustomDimensions,
    displayInList: shouldDisplayWidgetWithCustomDimensions,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CATEGORIES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top categories by pageviews', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Categories that your site visitors viewed the most', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Categories that your site visitors viewed the most', 'google-site-kit'),
    requiredCustomDimensions: ['googlesitekit_post_categories'],
    displayInSelectionPanel: shouldDisplayWidgetWithCustomDimensions,
    displayInWidgetArea: shouldDisplayWidgetWithCustomDimensions,
    displayInList: shouldDisplayWidgetWithCustomDimensions,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_POPULAR_CONTENT]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Most popular content by pageviews', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages that brought in the most visitors', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages your visitors read the most', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_POPULAR_PRODUCTS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Most popular products by pageviews', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Products that brought in the most visitors', 'google-site-kit'),
    requiredCustomDimensions: ['googlesitekit_post_type'],
    displayInSelectionPanel: ({
      select
    }) => select(_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.CORE_USER).isKeyMetricActive(_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_POPULAR_PRODUCTS) || select(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_SITE).getProductPostType(),
    displayInWidgetArea: shouldDisplayWidgetWithCustomDimensions,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_PAGES_PER_VISIT]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages per visit', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Number of pages visitors viewed per session on average', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Number of pages visitors viewed per session on average', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_VISIT_LENGTH]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Visit length', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Average duration of engaged visits', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Average duration of engaged visits', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_VISITS_PER_VISITOR]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Visits per visitor', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Average number of sessions per site visitor', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Average number of sessions per site visitor', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_MOST_ENGAGING_PAGES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Most engaging pages', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages with the highest engagement rate', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages with the highest engagement rate', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_LEAST_ENGAGING_PAGES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Least engaging pages', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages with the highest percentage of visitors that left without engagement with your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Percentage of visitors that left without engagement with your site', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_CONTENT_PERFORMANCE.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top pages by returning visitors', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages that attracted the most returning visitors', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages that attracted the most returning visitors', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_NEW_VISITORS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('New visitors', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('How many new visitors you got and how the overall audience changed', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Portion of visitors who visited your site for the first time in this timeframe', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_RETURNING_VISITORS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Returning visitors', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Portion of people who visited your site more than once', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Portion of your site’s visitors that returned at least once in this timeframe', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_VISITORS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top traffic source', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel which brought in the most visitors to your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in the most visitors to your site', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top traffic source driving add to cart', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel which brought in the most add to cart events to your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in the most add to cart events to your site', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.ADD_TO_CART],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top traffic source driving leads', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel which brought in the most leads to your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in the most leads to your site', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_GENERATING_LEADS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top traffic source driving purchases', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel which brought in the most purchases to your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in the most purchases to your site', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.PURCHASE],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Most engaged traffic source', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Visitors coming via this channel spent the most time on your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in the most visitors who had a meaningful engagement with your site', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top converting traffic source', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel which brought in the most visits that resulted in key events', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Channel (e.g. social, paid, search) that brought in visitors who generated the most key events', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CITIES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top cities driving traffic', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Which cities you get the most visitors from', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('The cities where most of your visitors came from', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top cities driving leads', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities driving the most contact form submissions', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities driving the most contact form submissions', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_GENERATING_LEADS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CITIES_DRIVING_ADD_TO_CART]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top cities driving add to cart', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities where visitors most frequently add products to their carts', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities where visitors most frequently add products to their carts', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.ADD_TO_CART],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top cities driving purchases', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities driving the most purchases', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Cities driving the most purchases', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.PURCHASE],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top device driving purchases', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top device driving the most purchases', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top device driving the most purchases', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.PURCHASE],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_SELLING_PRODUCTS.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_COUNTRIES]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top countries driving traffic', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Which countries you get the most visitors from', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('The countries where most of your visitors came from', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top performing keywords', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('What people searched for before they came to your site', 'google-site-kit'),
    infoTooltip: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('The top search queries for your site by highest clickthrough rate', 'google-site-kit'),
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_DRIVING_TRAFFIC.SLUG
    }
  },
  [_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_1__.KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS]: {
    title: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Top pages driving leads', 'google-site-kit'),
    description: (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_0__.__)('Pages on which forms are most frequently submitted', 'google-site-kit'),
    requiredConversionEventName: [_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_3__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD],
    displayInSelectionPanel: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    displayInList: _shouldDisplayWidgetWithConversionEvent__WEBPACK_IMPORTED_MODULE_4__.shouldDisplayWidgetWithConversionEvent,
    metadata: {
      group: _constants__WEBPACK_IMPORTED_MODULE_5__.KEY_METRICS_GROUP_GENERATING_LEADS.SLUG
    }
  }
};


/***/ }),

/***/ "./js/components/KeyMetrics/shouldDisplayWidgetWithConversionEvent.js":
/*!****************************************************************************!*\
  !*** ./js/components/KeyMetrics/shouldDisplayWidgetWithConversionEvent.js ***!
  \****************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   shouldDisplayWidgetWithConversionEvent: () => (/* binding */ shouldDisplayWidgetWithConversionEvent)
/* harmony export */ });
/* harmony import */ var _js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/js/googlesitekit/datastore/user/constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/js/modules/analytics-4/datastore/constants */ "./js/modules/analytics-4/datastore/constants.js");
/**
 * Key Metrics shouldDisplayWidgetWithConversionEvent function.
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */



/**
 * Determines whether to display a widget that requires conversion reporting events
 * in the key metrics selection panel.
 *
 * This function is attached to the widget object that requires the conversion reporting events and
 * has the `requiredConversionEventName` property.
 *
 * @since 1.136.0
 * @since 1.137.0 Moved function to its own file.
 *
 * @param {Object}   options        Options object.
 * @param {Function} options.select Data store select function.
 * @param {string}   options.slug   Key metric widget slug.
 * @return {boolean} Whether to display the widget.
 */
function shouldDisplayWidgetWithConversionEvent({
  select,
  slug
}) {
  return select(_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_1__.MODULES_ANALYTICS_4).hasConversionReportingEvents(
  // This property is available to the widget object that requires the
  // conversion reporting events, where the function is attached.
  this.requiredConversionEventName) || select(_js_googlesitekit_datastore_user_constants__WEBPACK_IMPORTED_MODULE_0__.CORE_USER).isKeyMetricActive(slug);
}

/***/ }),

/***/ "./js/feature-tours/index.js":
/*!***********************************!*\
  !*** ./js/feature-tours/index.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/**
 * Feature Tours.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Ordered tours.
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ([]);

/***/ }),

/***/ "./js/features/index.js":
/*!******************************!*\
  !*** ./js/features/index.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   enabledFeatures: () => (/* binding */ enabledFeatures),
/* harmony export */   isFeatureEnabled: () => (/* binding */ isFeatureEnabled)
/* harmony export */ });
/**
 * Feature flags.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const enabledFeatures = new Set(__webpack_require__.g?._googlesitekitBaseData?.enabledFeatures || []);

/**
 * Returns true if a feature is enabled; false otherwise.
 *
 * @since 1.25.0
 * @since 1.33.0 Changed _enabledFeatures argument to be a `Set` instead of `Array`.
 *
 * @param {string} feature            The name of the feature to check.
 * @param {Set}    [_enabledFeatures] Optional. The set of enabled features. Uses `enabledFeatures` set by the server in a global JS variable, by default.
 * @return {boolean} `true` if a feature is enabled; `false` otherwise.
 */
function isFeatureEnabled(feature, _enabledFeatures = enabledFeatures) {
  if (!(_enabledFeatures instanceof Set)) {
    return false;
  }
  return _enabledFeatures.has(feature);
}

/***/ }),

/***/ "./js/googlesitekit-datastore-user.js":
/*!********************************************!*\
  !*** ./js/googlesitekit-datastore-user.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _googlesitekit_datastore_user__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./googlesitekit/datastore/user */ "./js/googlesitekit/datastore/user/index.js");
/**
 * Entrypoint for the `core/user` data store.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */


(0,_googlesitekit_datastore_user__WEBPACK_IMPORTED_MODULE_1__.registerStore)((googlesitekit_data__WEBPACK_IMPORTED_MODULE_0___default()));

/***/ }),

/***/ "./js/googlesitekit/api/cache.js":
/*!***************************************!*\
  !*** ./js/googlesitekit/api/cache.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   STORAGE_KEY_PREFIX: () => (/* binding */ STORAGE_KEY_PREFIX),
/* harmony export */   STORAGE_KEY_PREFIX_ROOT: () => (/* binding */ STORAGE_KEY_PREFIX_ROOT),
/* harmony export */   clearCache: () => (/* binding */ clearCache),
/* harmony export */   deleteItem: () => (/* binding */ deleteItem),
/* harmony export */   getItem: () => (/* binding */ getItem),
/* harmony export */   getKeys: () => (/* binding */ getKeys),
/* harmony export */   getStorage: () => (/* binding */ getStorage),
/* harmony export */   isStorageAvailable: () => (/* binding */ isStorageAvailable),
/* harmony export */   resetDefaultStorageOrder: () => (/* binding */ resetDefaultStorageOrder),
/* harmony export */   setItem: () => (/* binding */ setItem),
/* harmony export */   setSelectedStorageBackend: () => (/* binding */ setSelectedStorageBackend),
/* harmony export */   setStorageOrder: () => (/* binding */ setStorageOrder)
/* harmony export */ });
/* harmony import */ var _js_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/js/util */ "./js/util/index.js");
/**
 * Caching functions and cache management for API requests.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */


/**
 * Prefix used for all Site Kit keys.
 *
 * Anything not using this prefix should not be touched by this library.
 *
 * @since 1.96.0
 * @private
 */
const STORAGE_KEY_PREFIX_ROOT = 'googlesitekit_';

/**
 * Prefix used for all Site Kit keys for the current Site Kit version.
 *
 * Anything not using this key should not be touched by this library.
 *
 * @since 1.5.0
 * @since 1.92.0 Updated to include a user, session, and blog-specific hash.
 * @since 1.96.0 Updated to make use of the new STORAGE_KEY_PREFIX_ROOT constant.
 * @private
 */
const STORAGE_KEY_PREFIX = `${STORAGE_KEY_PREFIX_ROOT}${"1.168.0"}_${__webpack_require__.g._googlesitekitBaseData.storagePrefix}_`;
const defaultOrder = ['sessionStorage', 'localStorage'];
let storageBackend;
let storageOrder = [...defaultOrder];

/**
 * Overrides the storage backend.
 *
 * Largely used for tests. Should not be used directly.
 *
 * @since 1.5.0
 * @private
 *
 * @param {*} backend Backend to set for the cache.
 */
function setSelectedStorageBackend(backend) {
  storageBackend = backend;
}

/**
 * Overrides the priority of storage mechanisms.
 *
 * Largely used for tests. Implicitly resets the selected storage backend,
 * causing `_getStorage` to re-run its checks for the best available
 * storage backend.
 *
 * @since 1.5.0
 * @private
 *
 * @param {Array} order Ordered array of storage backends to use.
 */
function setStorageOrder(order) {
  storageOrder = [...order];
  setSelectedStorageBackend(undefined);
}

/**
 * Resets the storage mechanism order.
 *
 * Largely used for tests. Implicitly resets the selected storage backend,
 * causing `_getStorage` to re-run its checks for the best available
 * storage backend.
 *
 * @since 1.5.0
 * @private
 */
function resetDefaultStorageOrder() {
  storageOrder = [...defaultOrder];
  setSelectedStorageBackend(undefined);
}

/**
 * Detects whether browser storage is both supported and available.
 *
 * @since 1.5.0
 * @private
 *
 * @param {string} type Browser storage to test. Should be one of `localStorage` or `sessionStorage`.
 * @return {boolean} True if the given storage is available, false otherwise.
 */
// eslint-disable-next-line require-await
async function isStorageAvailable(type) {
  const storage = __webpack_require__.g[type];
  if (!storage) {
    return false;
  }
  try {
    const x = '__storage_test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return e instanceof DOMException && (
    // everything except Firefox
    22 === e.code ||
    // Firefox
    1014 === e.code ||
    // test name field too, because code might not be present
    // everything except Firefox
    'QuotaExceededError' === e.name ||
    // Firefox
    'NS_ERROR_DOM_QUOTA_REACHED' === e.name) &&
    // acknowledge QuotaExceededError only if there's something already stored
    0 !== storage.length;
  }
}

/**
 * Gets the storage object to use.
 *
 * @since 1.5.0
 * @private
 *
 * @return {Storage|null} A storage mechanism (`localStorage` or `sessionStorage`) if available; otherwise returns `null`.
 */
async function getStorage() {
  if (storageBackend !== undefined) {
    return storageBackend;
  }

  // Only run the logic to determine the storage object once.
  for (const backend of storageOrder) {
    if (storageBackend) {
      continue;
    }
    if (await isStorageAvailable(backend)) {
      storageBackend = __webpack_require__.g[backend];
    }
  }
  if (storageBackend === undefined) {
    storageBackend = null;
  }
  return storageBackend;
}

/**
 * Gets cached data.
 *
 * Get cached data from the persistent storage cache.
 *
 * @since 1.5.0
 *
 * @param {string} key Name of cache key.
 * @return {Promise} A promise returned, containing an object with the cached value (if found) and whether or not there was a cache hit.
 */
async function getItem(key) {
  const storage = await getStorage();
  if (storage) {
    const cachedData = storage.getItem(`${STORAGE_KEY_PREFIX}${key}`);
    if (cachedData) {
      const parsedData = JSON.parse(cachedData);
      const {
        timestamp,
        ttl,
        value,
        isError
      } = parsedData;

      // Ensure a timestamp is found, otherwise this isn't a valid cache hit.
      // (We don't check for a truthy `value`, because it could be legitimately
      // false-y if `0`, `null`, etc.)
      if (timestamp && (!ttl ||
      // Ensure the cached data isn't too old.
      // The cache dates shouldn't rely on reference
      // dates for cache expiration. This is a case
      // where we actually want to rely on
      // the _actual_ date/time the data was set.
      Math.round(Date.now() / 1000) - timestamp < ttl) // eslint-disable-line sitekit/no-direct-date
      ) {
        return {
          cacheHit: true,
          value,
          isError
        };
      }
    }
  }
  return {
    cacheHit: false,
    value: undefined
  };
}

/**
 * Sets cached data using a key.
 *
 * Save data to the relevant local storage mechanism, if available.
 * By default, data is saved with a one hour (60 minute) TTL.
 *
 * @since 1.5.0
 *
 * @param {string}  key              Name of cache key.
 * @param {*}       value            Value to store in the cache.
 * @param {Object}  args             Optional object containing ttl, timestamp and isError keys.
 * @param {number}  [args.ttl]       Optional. Validity of the cached item in seconds.
 * @param {number}  [args.timestamp] Optional. Timestamp when the cached item was created.
 * @param {boolean} [args.isError]   Optional. Whether the cached item is an error.
 * @return {Promise} A promise: resolves to `true` if the value was saved; `false` if not (usually because no storage method was available).
 */
async function setItem(key, value, {
  ttl = _js_util__WEBPACK_IMPORTED_MODULE_0__.HOUR_IN_SECONDS,
  // Cached times should rely on real times, not the reference date,
  // so the cache timeouts are consistent even when changing
  // the reference dates when developing/testing.
  timestamp = Math.round(Date.now() / 1000),
  // eslint-disable-line sitekit/no-direct-date
  isError = false
} = {}) {
  const storage = await getStorage();
  if (storage) {
    try {
      storage.setItem(`${STORAGE_KEY_PREFIX}${key}`, JSON.stringify({
        timestamp,
        ttl,
        value,
        isError
      }));
      return true;
    } catch (error) {
      __webpack_require__.g.console.warn('Encountered an unexpected storage error:', error);
      return false;
    }
  }
  return false;
}

/**
 * Removes cached data by key.
 *
 * Remove one piece of cached data from the persistent storage cache, by key.
 *
 * @since 1.5.0
 *
 * @param {string} key Name of cache key.
 * @return {Promise} A promise: resolves to `true` if the value was deleted; `false` if not (usually because no storage method was available).
 */
async function deleteItem(key) {
  const storage = await getStorage();
  if (storage) {
    try {
      const fullKey = key.startsWith(STORAGE_KEY_PREFIX_ROOT) ? key : `${STORAGE_KEY_PREFIX}${key}`;
      storage.removeItem(fullKey);
      return true;
    } catch (error) {
      __webpack_require__.g.console.warn('Encountered an unexpected storage error:', error);
      return false;
    }
  }
  return false;
}

/**
 * Gets all cache keys created by Site Kit.
 *
 * @since 1.5.0
 *
 * @return {Promise} A promise: resolves to an array of all keys.
 */
async function getKeys() {
  const storage = await getStorage();
  if (storage) {
    try {
      const keys = [];
      for (let i = 0; i < storage.length; i++) {
        const itemKey = storage.key(i);
        if (itemKey.indexOf(STORAGE_KEY_PREFIX_ROOT) === 0) {
          keys.push(itemKey);
        }
      }
      return keys;
    } catch (error) {
      __webpack_require__.g.console.warn('Encountered an unexpected storage error:', error);
      return [];
    }
  }
  return [];
}

/**
 * Removes the entire cache created by Site Kit.
 *
 * @since 1.5.0
 *
 * @return {Promise} A promise: resolves to `true` if the cache was cleared; `false` if there was an error.
 */
async function clearCache() {
  const storage = await getStorage();
  if (storage) {
    const keys = await getKeys();
    for (const key of keys) {
      await deleteItem(key);
    }
    return true;
  }
  return false;
}

/***/ }),

/***/ "./js/googlesitekit/data/create-error-store.js":
/*!*****************************************************!*\
  !*** ./js/googlesitekit/data/create-error-store.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   createErrorStore: () => (/* binding */ createErrorStore),
/* harmony export */   generateErrorKey: () => (/* binding */ generateErrorKey)
/* harmony export */ });
/* harmony import */ var _wordpress_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @wordpress/data */ "../node_modules/@wordpress/data/build-module/factory.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! md5 */ "../node_modules/md5/md5.js");
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(md5__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _js_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/js/util */ "./js/util/index.js");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/**
 * API function to create fetch store.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */


/**
 * External dependencies
 */


const RECEIVE_ERROR = 'RECEIVE_ERROR';
const CLEAR_ERROR = 'CLEAR_ERROR';
const CLEAR_ERRORS = 'CLEAR_ERRORS';

/**
 * Internal dependencies
 */


function generateErrorKey(baseName, args) {
  if (args && Array.isArray(args)) {
    const stringifiedArgs = args.map(item => {
      return 'object' === typeof item ? (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.stringifyObject)(item) : item;
    });
    return `${baseName}::${md5__WEBPACK_IMPORTED_MODULE_1___default()(JSON.stringify(stringifiedArgs))}`;
  }
  return baseName;
}
const actions = {
  receiveError(error, baseName, args = []) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(error, 'error is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(baseName, 'baseName is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(args && Array.isArray(args), 'args must be an array.');
    return {
      type: RECEIVE_ERROR,
      payload: {
        error,
        baseName,
        args
      }
    };
  },
  clearError(baseName, args = []) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(baseName, 'baseName is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(args && Array.isArray(args), 'args must be an array.');
    return {
      type: CLEAR_ERROR,
      payload: {
        baseName,
        args
      }
    };
  },
  clearErrors(baseName) {
    return {
      type: CLEAR_ERRORS,
      payload: {
        baseName
      }
    };
  }
};
function createErrorStore(storeName) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(storeName, 'storeName must be defined.');
  const initialState = {
    errors: {},
    errorArgs: {}
  };
  const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, {
    type,
    payload
  }) => {
    switch (type) {
      case RECEIVE_ERROR:
        {
          const {
            baseName,
            args,
            error
          } = payload;
          const key = generateErrorKey(baseName, args);
          state.errors = state.errors || {};
          state.errorArgs = state.errorArgs || {};
          state.errors[key] = error;
          state.errorArgs[key] = args;
          break;
        }
      case CLEAR_ERROR:
        {
          const {
            baseName,
            args
          } = payload;
          const key = generateErrorKey(baseName, args);
          state.errors = state.errors || {};
          state.errorArgs = state.errorArgs || {};
          delete state.errors[key];
          delete state.errorArgs[key];
          break;
        }
      case CLEAR_ERRORS:
        {
          const {
            baseName
          } = payload;
          if (baseName) {
            state.errors = state.errors || {};
            state.errorArgs = state.errorArgs || {};
            for (const key in state.errors) {
              if (key === baseName || key.startsWith(`${baseName}::`)) {
                delete state.errors[key];
                delete state.errorArgs[key];
              }
            }
          } else {
            state.errors = {};
            state.errorArgs = {};
          }
          break;
        }
    }
  });
  const controls = {};
  const resolvers = {};
  const selectors = {
    /**
     * Retrieves the error object from state.
     *
     * Error object has the format:
     *
     * ```
     * {
     *   code: <String>,
     *   message: <String>,
     *   data: <Object>
     * }
     * ```
     *
     * @since 1.15.0
     *
     * @param {Object}      state        Data store's state.
     * @param {string}      selectorName Selector name.
     * @param {Array.<any>} [args]       Arguments passed to selector (default `[]`).
     * @return {(Object|undefined)} Error object if exists, otherwise undefined.
     */
    getErrorForSelector(state, selectorName, args = []) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(selectorName, 'selectorName is required.');
      return selectors.getError(state, selectorName, args);
    },
    /**
     * Retrieves the error object from state.
     *
     *```
     * {
     *   code: <String>,
     *   message: <String>,
     *   data: <Object>
     * }
     * ```
     *
     * @since 1.15.0
     *
     * @param {Object}      state      Data store's state.
     * @param {string}      actionName Action name.
     * @param {Array.<any>} [args]     Arguments passed to action (default `[]`).
     * @return {(Object|undefined)} Error object if exists, otherwise undefined.
     */
    getErrorForAction(state, actionName, args = []) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(actionName, 'actionName is required.');
      return selectors.getError(state, actionName, args);
    },
    /**
     * Retrieves the error object from state.
     *
     *```
     * {
     *   code: <String>,
     *   message: <String>,
     *   data: <Object>
     * }
     * ```
     *
     * @since 1.15.0
     * @private
     *
     * @param {Object}      state      Data store's state.
     * @param {string}      [baseName] Selector or action name.
     * @param {Array.<any>} [args]     Arguments array.
     * @return {(Object|undefined)} Error object if exists, otherwise undefined.
     */
    getError(state, baseName, args) {
      const {
        errors
      } = state;
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(baseName, 'baseName is required.');
      return errors[generateErrorKey(baseName, args)];
    },
    /**
     * Gets a list of all unique errors.
     *
     * @since 1.19.0
     *
     * @param {Object} state Data store's state.
     * @return {Object[]} Unique set of errors.
     */
    getErrors(state) {
      const errorsSet = new Set(Object.values(state.errors));
      return Array.from(errorsSet);
    },
    /**
     * Gets the meta-data for a given error object, or null if the error is not found.
     *
     * Returns meta-data in the format:
     *
     * ```
     *	{
     *		baseName: <string>,
     *		args: <Array>
     *	}
     * ```
     *
     * @since 1.84.0
     *
     * @param {Object} state Data store's state.
     * @param {Object} error Error object.
     * @return {Object|null} Meta-data for the given error object, or null if the error is not found.
     */
    getMetaDataForError(state, error) {
      const key = Object.keys(state.errors).find(errorKey => state.errors[errorKey] === error);
      if (key) {
        const baseName = key.substring(0, key.indexOf('::'));
        return {
          baseName,
          args: state.errorArgs[key]
        };
      }
      return null;
    },
    /**
     * Gets the selector data for a given error object, or null if no selector data is available.
     *
     * Returns selector data in the format:
     *
     * ```
     *	{
     *		storeName: <string>,
     *		name: <string>,
     *		args: <Array>
     *	}
     * ```
     *
     * @since 1.87.0
     *
     * @param {Object} state Data store's state.
     * @param {Object} error Error object.
     * @return {Object|null} Selector data for the given error object, or null if no selector data is available.
     */
    getSelectorDataForError: (0,_wordpress_data__WEBPACK_IMPORTED_MODULE_4__.createRegistrySelector)(select => function (state, error) {
      const metaData = select(storeName).getMetaDataForError(error);
      if (metaData) {
        const {
          baseName: name,
          args
        } = metaData;
        const isSelector = !!select(storeName)[name];
        if (isSelector) {
          return {
            storeName,
            name,
            args
          };
        }
      }
      return null;
    }),
    /**
     * Determines whether the datastore has errors or not.
     *
     * @since 1.15.0
     *
     * @param {Object} state Data store's state.
     * @return {boolean} TRUE if the datastore has errors, otherwise FALSE.
     */
    hasErrors(state) {
      return selectors.getErrors(state).length > 0;
    }
  };
  return {
    initialState,
    actions,
    controls,
    reducer,
    resolvers,
    selectors
  };
}

/***/ }),

/***/ "./js/googlesitekit/data/create-fetch-store.js":
/*!*****************************************************!*\
  !*** ./js/googlesitekit/data/create-fetch-store.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createFetchStore: () => (/* binding */ createFetchStore)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _create_error_store__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/* harmony import */ var _transform_case__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./transform-case */ "./js/googlesitekit/data/transform-case.js");
/* harmony import */ var _js_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/util */ "./js/util/index.js");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_5__);
/**
 * API function to create fetch store.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */




function defaultReducerCallback(state) {
  return state;
}
function defaultArgsToParams() {
  return {};
}
function defaultValidateParams() {}

// Get access to error store action creators.
// If the parent store doesn't include the error store,
// yielded error actions will be a no-op.
const {
  clearError,
  receiveError
} = _create_error_store__WEBPACK_IMPORTED_MODULE_2__.actions;

/**
 * Creates a store object implementing the necessary infrastructure for a
 * single fetch action.
 *
 * This function returns a partial store object with the following:
 * - action creators to fetch and to receive the data
 * - control to issue the API request
 * - reducer to set API request flag and receive the response
 * - selector to check whether the API request is in progress via a flag
 *
 * The names of the pieces are based on the baseName provided.
 * For example, if baseName is 'saveSettings':
 * - The fetch action creator is called 'fetchSaveSettings'.
 * - The receive action creator is called 'receiveSaveSettings'.
 * - The fetching selector is called 'isFetchingSaveSettings'.
 *
 * All parts of the returned store objects should be considered internal. A
 * public action or selector should be implemented to actually call the
 * fetch action included in the returned store object.
 *
 * For example, if the fetch store is intended for an API-based
 * action 'storeMySetting':
 * - The basename passed should be 'storeMySetting'.
 * - The action 'storeMySetting' should call 'fetchStoreMySetting'.
 *
 * Or, if the fetch store is intended for an API-based selector
 * 'getSomeData':
 * - The baseName passed should be 'getSomeData'.
 * - The resolver for 'getSomeData' should call 'fetchGetSomeData'.
 *
 * @since 1.10.0
 * @private
 *
 * @param {Object}   args                   Arguments for creating the fetch store.
 * @param {string}   args.baseName          The base name to use for all the created infrastructure.
 * @param {Function} args.controlCallback   Callback function to issue the API request. Will be used inside the
 *                                          control. The function receives a params object based on argsToParams,
 *                                          i.e. the respective values passed to the action.
 * @param {Function} [args.reducerCallback] Optional. Callback function to modify state based on the API response.
 *                                          Will be used inside the reducer. The function receives the store's state
 *                                          object as first parameter, the API response as second parameter, and the
 *                                          params object for the request (see above) as third parameter. If not
 *                                          provided, the default will return the unmodified state.
 * @param {Function} [args.argsToParams]    Optional. Function that reduces the given list of arguments
 *                                          into a object of key/value parameters, with the argument names used as keys.
 *                                          If not provided, the default function will return an empty object,
 *                                          essentially indicating that no arguments are supported/required.
 * @param {Function} [args.validateParams]  Optional. Function that validates the given parameters object created by `argsToParams`.
 *                                          Any invalid parameters should cause a respective error to be thrown.
 * @return {Object} Partial store object with properties 'actions', 'controls', 'reducer', 'resolvers', and 'selectors'.
 */
function createFetchStore({
  baseName,
  controlCallback,
  reducerCallback = defaultReducerCallback,
  argsToParams = defaultArgsToParams,
  validateParams = defaultValidateParams
}) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(baseName, 'baseName is required.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()('function' === typeof controlCallback, 'controlCallback is required and must be a function.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()('function' === typeof reducerCallback, 'reducerCallback must be a function.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()('function' === typeof argsToParams, 'argsToParams must be a function.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()('function' === typeof validateParams, 'validateParams must be a function.');

  // If validating the result of argsToParams without any arguments does not result in an error, we
  // know params is okay to be empty.
  let requiresParams;
  try {
    validateParams(argsToParams());
    requiresParams = false;
  } catch (error) {
    requiresParams = true;
  }
  const pascalCaseBaseName = (0,_transform_case__WEBPACK_IMPORTED_MODULE_3__.camelCaseToPascalCase)(baseName);
  const constantBaseName = (0,_transform_case__WEBPACK_IMPORTED_MODULE_3__.camelCaseToConstantCase)(baseName);
  const FETCH = `FETCH_${constantBaseName}`;
  const START_FETCH = `START_${FETCH}`;
  const FINISH_FETCH = `FINISH_${FETCH}`;
  const CATCH_FETCH = `CATCH_${FETCH}`;
  const RECEIVE = `RECEIVE_${constantBaseName}`;
  const fetchCreator = `fetch${pascalCaseBaseName}`;
  const receiveCreator = `receive${pascalCaseBaseName}`;
  const isFetching = `isFetching${pascalCaseBaseName}`;
  const initialState = {
    [isFetching]: {}
  };
  function* fetchGenerator(params, args) {
    let response;
    let error;
    yield {
      payload: {
        params
      },
      type: START_FETCH
    };
    yield clearError(baseName, args);
    try {
      response = yield {
        payload: {
          params
        },
        type: FETCH
      };
      yield actions[receiveCreator](response, params);
      yield {
        payload: {
          params
        },
        type: FINISH_FETCH
      };
    } catch (e) {
      error = e;
      yield receiveError(error, baseName, args);
      yield {
        payload: {
          params
        },
        type: CATCH_FETCH
      };
    }
    return {
      response,
      error
    };
  }
  const actions = {
    [fetchCreator](...args) {
      const params = argsToParams(...args);
      // In order for params validation to throw an error as expected,
      // this function cannot be a generator.
      validateParams(params);

      // The normal fetch action generator is invoked as the return here
      // to preserve asynchronous behavior without registering another action creator.
      return fetchGenerator(params, args);
    },
    [receiveCreator](response, params) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(response !== undefined, 'response is required.');
      if (requiresParams) {
        invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(params), 'params is required.');
        validateParams(params);
      } else {
        params = {};
      }
      return {
        payload: {
          response,
          params
        },
        type: RECEIVE
      };
    }
  };
  const controls = {
    [FETCH]: ({
      payload
    }) => {
      return controlCallback(payload.params);
    }
  };
  const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_5__.createReducer)((state, {
    type,
    payload
  }) => {
    switch (type) {
      case START_FETCH:
        {
          const {
            params
          } = payload;
          state[isFetching] = state[isFetching] || {};
          state[isFetching][(0,_js_util__WEBPACK_IMPORTED_MODULE_4__.stringifyObject)(params)] = true;
          return state;
        }
      case RECEIVE:
        {
          const {
            response,
            params
          } = payload;
          return reducerCallback(state, response, params);
        }
      case FINISH_FETCH:
        {
          const {
            params
          } = payload;
          state[isFetching] = state[isFetching] || {};
          state[isFetching][(0,_js_util__WEBPACK_IMPORTED_MODULE_4__.stringifyObject)(params)] = false;
          return state;
        }
      case CATCH_FETCH:
        {
          const {
            params
          } = payload;
          state[isFetching] = state[isFetching] || {};
          state[isFetching][(0,_js_util__WEBPACK_IMPORTED_MODULE_4__.stringifyObject)(params)] = false;
          return state;
        }
      default:
        return state;
    }
  });
  const selectors = {
    [isFetching]: (state, ...args) => {
      if (state[isFetching] === undefined) {
        return false;
      }
      let params;
      try {
        params = argsToParams(...args);
        validateParams(params);
      } catch (err) {
        // If parameters are invalid, fail silently here. It likely is
        // because some dependency selector is still resolving.
        return false;
      }
      return !!state[isFetching][(0,_js_util__WEBPACK_IMPORTED_MODULE_4__.stringifyObject)(params)];
    }
  };
  return {
    initialState,
    actions,
    controls,
    reducer,
    resolvers: {},
    selectors
  };
}

/***/ }),

/***/ "./js/googlesitekit/data/create-notifications-store.js":
/*!*************************************************************!*\
  !*** ./js/googlesitekit/data/create-notifications-store.js ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createNotificationsStore: () => (/* binding */ createNotificationsStore)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _create_fetch_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/**
 * Provides API functions to create a datastore for notifications.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */




/**
 * Creates a store object that includes actions and selectors for managing notifications.
 *
 * The three required parameters hook up the store to the respective REST API endpoint.
 *
 * @since 1.6.0
 * @private
 *
 * @param {string}  type              The data to access. One of 'core' or 'modules'.
 * @param {string}  identifier        The data identifier, eg. a module slug like search-console.
 * @param {string}  datapoint         The endpoint to request data from, e.g. 'notifications'.
 * @param {Object}  options           Optional. Options to consider for the store.
 * @param {boolean} options.server    Enable server notifications. `true` by default.
 * @param {number}  options.storeName Store name to use. Default is '{type}/{identifier}'.
 * @return {Object} The notifications store object, with additional `STORE_NAME` and
 *                  `initialState` properties.
 */
function createNotificationsStore(type, identifier, datapoint, {
  server = true,
  storeName = undefined
} = {}) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(type, 'type is required.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(identifier, 'identifier is required.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(datapoint, 'datapoint is required.');
  const STORE_NAME = storeName || `${type}/${identifier}`;
  const initialState = {
    serverNotifications: server ? undefined : {}
  };
  const fetchGetNotificationsStore = (0,_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
    baseName: 'getNotifications',
    controlCallback: () => {
      return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.get)(type, identifier, datapoint);
    },
    reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, notifications) => {
      state.serverNotifications = notifications.reduce((acc, notification) => {
        return {
          ...acc,
          [notification.id]: notification
        };
      }, {});
    })
  });
  const actions = {};
  const controls = {};

  // eslint-disable-next-line no-shadow
  function reducer(state = initialState, {
    type
  }) {
    switch (type) {
      default:
        {
          return state;
        }
    }
  }
  const resolvers = {
    *getNotifications() {
      const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
      const notifications = registry.select(STORE_NAME).getNotifications();
      if (!notifications) {
        yield fetchGetNotificationsStore.actions.fetchGetNotifications();
      }
    }
  };

  // If server notifications are disabled, we should remove the getNotifications
  // resolver. If we set it as `undefined` we'll encounter issues with an `undefined`
  // resolver, because @wordpress/data will still try to register the resolver because
  // it sees a key. And this is nicer than a no-op resolver.
  if (!server) {
    delete resolvers.getNotifications;
  }
  const selectors = {
    /**
     * Gets the current notifications.
     *
     * Returns `undefined` if notifications are not available/loaded.
     *
     * @since 1.6.0
     *
     * @param {Object} state Data store's state.
     * @return {(Array|undefined)} Current list of notifications.
     */
    getNotifications(state) {
      const {
        serverNotifications
      } = state;

      // If there are no client notifications and the server notifications
      // haven't loaded yet, return `undefined` (the value of
      // `serverNotifications` here) to signify to anything using this
      // selector that notifications have not loaded yet.
      if ('undefined' === typeof serverNotifications) {
        return serverNotifications;
      }

      // If there are any notifications from either the client or server,
      // we should return them, even if the server notifications haven't
      // finished loading yet.
      return Object.values({
        ...(serverNotifications || {})
      });
    }
  };
  const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.combineStores)(fetchGetNotificationsStore, {
    initialState,
    actions,
    controls,
    reducer,
    resolvers,
    selectors
  });
  return {
    ...store,
    STORE_NAME
  };
}

/***/ }),

/***/ "./js/googlesitekit/data/transform-case.js":
/*!*************************************************!*\
  !*** ./js/googlesitekit/data/transform-case.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   camelCaseToConstantCase: () => (/* binding */ camelCaseToConstantCase),
/* harmony export */   camelCaseToPascalCase: () => (/* binding */ camelCaseToPascalCase),
/* harmony export */   hyphenCaseToPascalCase: () => (/* binding */ hyphenCaseToPascalCase)
/* harmony export */ });
/**
 * Data store utilities for transforming names to a certain case.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Transforms a camelCase name into its PascalCase name.
 *
 * @since 1.10.0
 * @private
 *
 * @param {string} name "camelCase" name to transform.
 * @return {string} PascalCase name.
 */
function camelCaseToPascalCase(name) {
  return name.charAt(0).toUpperCase() + name.slice(1);
}

/**
 * Transforms a camelCase name into its CONSTANT_CASE name.
 *
 * @since 1.10.0
 * @private
 *
 * @param {string} name "camelCase" name to transform.
 * @return {string} CONSTANT_CASE name.
 */
function camelCaseToConstantCase(name) {
  return name.replace(/([a-z0-9]{1})([A-Z]{1})/g, '$1_$2').toUpperCase();
}

/**
 * Transforms a hyphen-case name into its PascalCase name.
 *
 * @since 1.30.0
 * @private
 *
 * @param {string} name "hyphen-case" name to transform.
 * @return {string} PascalCase name.
 */
function hyphenCaseToPascalCase(name) {
  return name.split('-').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
}

/***/ }),

/***/ "./js/googlesitekit/data/utils.js":
/*!****************************************!*\
  !*** ./js/googlesitekit/data/utils.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   collect: () => (/* binding */ collect),
/* harmony export */   collectActions: () => (/* binding */ collectActions),
/* harmony export */   collectControls: () => (/* binding */ collectControls),
/* harmony export */   collectName: () => (/* binding */ collectName),
/* harmony export */   collectReducers: () => (/* binding */ collectReducers),
/* harmony export */   collectResolvers: () => (/* binding */ collectResolvers),
/* harmony export */   collectSelectors: () => (/* binding */ collectSelectors),
/* harmony export */   collectState: () => (/* binding */ collectState),
/* harmony export */   combineStores: () => (/* binding */ combineStores),
/* harmony export */   commonActions: () => (/* binding */ commonActions),
/* harmony export */   commonControls: () => (/* binding */ commonControls),
/* harmony export */   commonStore: () => (/* binding */ commonStore),
/* harmony export */   createStrictSelect: () => (/* binding */ createStrictSelect),
/* harmony export */   createValidatedAction: () => (/* binding */ createValidatedAction),
/* harmony export */   createValidationSelector: () => (/* binding */ createValidationSelector)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! memize */ "../node_modules/memize/index.js");
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(memize__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _wordpress_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @wordpress/data */ "../node_modules/@wordpress/data/build-module/factory.js");
/**
 * Data store utilities.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */




/**
 * WordPress dependencies
 */

const GET_REGISTRY = 'GET_REGISTRY';
const AWAIT = 'AWAIT';

/**
 * Collects and combines multiple objects of similar shape.
 *
 * Used to combine objects like actions, selectors, etc. for a data
 * store while ensuring no keys/action names/selector names are duplicated.
 *
 * Effectively this is an object spread, but throws an error if keys are
 * duplicated.
 *
 * @since 1.5.0
 * @private
 *
 * @param {...Object} items A list of arguments, each one should be an object to combine into one.
 * @return {Object} The combined object.
 */
function collect(...items) {
  const collectedObject = items.reduce((acc, item) => {
    return {
      ...acc,
      ...item
    };
  }, {});
  const functionNames = items.reduce((acc, itemSet) => {
    return [...acc, ...Object.keys(itemSet)];
  }, []);
  const duplicates = findDuplicates(functionNames);
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(duplicates.length === 0, `collect() cannot accept collections with duplicate keys. Your call to collect() contains the following duplicated functions: ${duplicates.join(', ')}. Check your data stores for duplicates.`);
  return collectedObject;
}

/**
 * Collects all actions.
 *
 * @since 1.5.0
 *
 * @param {...Object} args A list of objects, each containing their own actions.
 * @return {Object} The combined object.
 */
const collectActions = collect;

/**
 * Collects all controls.
 *
 * @since 1.5.0
 *
 * @param {...Object} args A list of objects, each containing their own controls.
 * @return {Object} The combined object.
 */
const collectControls = collect;

/**
 * Collects all reducers and (optionally) provides initial state.
 *
 * If the first argument passed is not a function, it will be used as the
 * combined reducer's `initialState`.
 *
 * @since 1.5.0
 *
 * @param {...(Object|Function)} args A list of reducers, each containing their own controls. If the first argument is not a function, it will be used as the combined reducer's `initialState`.
 * @return {Function} A Redux-style reducer.
 */
function collectReducers(...args) {
  const reducers = [...args];
  let initialState;
  if (typeof reducers[0] !== 'function') {
    initialState = reducers.shift();
  }
  return (state = initialState, action = {}) => {
    return reducers.reduce((newState, reducer) => {
      return reducer(newState, action);
    }, state);
  };
}

/**
 * Collects all resolvers.
 *
 * @since 1.5.0
 *
 * @param {...Object} args A list of objects, each containing their own resolvers.
 * @return {Object} The combined object.
 */
const collectResolvers = collect;

/**
 * Collects all selectors.
 *
 * @since 1.5.0
 *
 * @param {...Object} args A list of objects, each containing their own selectors.
 * @return {Object} The combined object.
 */
const collectSelectors = collect;

/**
 * Collects all state values.
 *
 * @since 1.5.0
 *
 * @param {...Object} args A list of objects, each containing their own state values.
 * @return {Object} The combined object.
 */
const collectState = collect;

/**
 * Collects all store names.
 *
 * This function's main purpose is to ensure generated store names for a single store match.
 *
 * @since 1.6.0
 *
 * @param {...string} args A list of store names, all of which must be equal.
 * @return {string} The single store name.
 */
function collectName(...args) {
  const names = [...args];
  const duplicates = findDuplicates(names);
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(duplicates.length === names.length - 1, 'collectName() must not receive different names.');
  return names.shift();
}

/**
 * Passes through state unmodified; eg. an empty reducer.
 *
 * @since 1.8.0
 * @private
 *
 * @param {Object} state A store's state.
 * @return {Object} The same state data as passed in `state`.
 */
function passthroughReducer(state) {
  return state;
}

/**
 * Combines multiple stores.
 *
 * @since 1.8.0
 *
 * @param {...Object} stores A list of objects, each a store containing one or more of the following keys: initialState, actions, controls, reducer, resolvers, selectors.
 * @return {Object} The combined store.
 */
function combineStores(...stores) {
  const combinedInitialState = collectState(...stores.map(store => store.initialState || {}));
  return {
    initialState: combinedInitialState,
    controls: collectControls(...stores.map(store => store.controls || {})),
    actions: collectActions(...stores.map(store => store.actions || {})),
    reducer: collectReducers(combinedInitialState, ...stores.map(store => store.reducer || passthroughReducer)),
    resolvers: collectResolvers(...stores.map(store => store.resolvers || {})),
    selectors: collectSelectors(...stores.map(store => store.selectors || {}))
  };
}

/**
 * An object of common actions most stores will use.
 *
 * @since 1.7.0
 *
 * @return {Object} Key/value list of common actions most stores will want.
 */
const commonActions = {
  /**
   * Dispatches an action and calls a control to get the current data registry.
   *
   * Useful for controls and resolvers that wish to dispatch actions/use selectors
   * on the current data registry.
   *
   * @since 1.7.0
   *
   * @return {Object} FSA-compatible action.
   */
  getRegistry() {
    return {
      payload: {},
      type: GET_REGISTRY
    };
  },
  /**
   * Dispatches an action and calls a control to return the promise resolution.
   *
   * Useful for controls and resolvers that wish to call an asynchronous function or other promise.
   *
   * @since 1.22.0
   *
   * @param {Promise} value A promise to resolve.
   * @return {Object} Object with resolved promise.
   */
  *await(value) {
    return {
      payload: {
        value
      },
      type: AWAIT
    };
  }
};

/**
 * An object of common controls most stores will use.
 *
 * @since 1.7.0
 *
 * @return {Object} Key/value list of common controls most stores will want.
 */
const commonControls = {
  /**
   * Returns the current registry.
   *
   * Useful for controls and resolvers that wish to dispatch actions/use selectors
   * on the current data registry.
   *
   * @since 1.7.0
   *
   * @return {Object} FSA-compatible action.
   */
  [GET_REGISTRY]: (0,_wordpress_data__WEBPACK_IMPORTED_MODULE_3__.createRegistryControl)(registry => () => registry),
  /**
   * Returns a resolved promise.
   *
   * @since 1.22.0
   *
   * @param {Object} payload         Object containing a promise.
   * @param {Object} payload.payload Object containing a promise.
   * @return {*} Resolved promise.
   */
  [AWAIT]: ({
    payload
  }) => payload.value
};

/**
 * Finds all duplicate items in an array and return them.
 *
 * @since 1.5.0
 * @private
 *
 * @param {Array} array Any array.
 * @return {Array} All values in the input array that were duplicated.
 */
function findDuplicates(array) {
  const duplicates = [];
  const counts = {};
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
    if (counts[item] > 1) {
      duplicates.push(item);
    }
  }
  return duplicates;
}

/**
 * A store containing the common actions, controls and reducer that all stores will use.
 *
 * @since 1.8.0
 *
 * @return {Object} Object with common actions, controls and reducer.
 */
const commonStore = {
  actions: commonActions,
  controls: commonControls,
  reducer: passthroughReducer
};

/**
 * Creates a strict version of registry.select for ensuring that a selector is resolved at the time of calling.
 *
 * Not intended to be used directly. This is useful in the context of validation functions
 * to save checking for undefined on every result.
 *
 * Given the registry.select function instance, a new function is returned
 * with the same API as `select()` but will throw an error if the result
 * of the selector function is `undefined`.
 *
 * Ideally this would use something like `hasFinishedResolution` instead,
 * but there is no way to traverse the selectors used internally to identify
 * dependent selectors that have resolvers as many selectors are composed of
 * higher-level selectors internally which is where a resolver is normally implemented.
 *
 * @since 1.18.0
 * @private
 *
 * @param {Function} select The registry.select function.
 * @return {Function} The strict version of registry.select.
 */
function createStrictSelect(select) {
  return storeName => {
    return getStrictSelectors(select(storeName));
  };
}

// Based on {@link https://github.com/WordPress/gutenberg/blob/b1c8026087dfb026eff0a023a5f7febe28c876de/packages/data/src/registry.js#L91}
const getStrictSelectors = memize__WEBPACK_IMPORTED_MODULE_1___default()(selectors => (0,lodash__WEBPACK_IMPORTED_MODULE_2__.mapValues)(selectors, (selector, selectorName) => (...args) => {
  const returnValue = selector(...args);
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(returnValue !== undefined, `${selectorName}(...) is not resolved`);
  return returnValue;
}));

/**
 * Creates two registry selectors that call the incoming function to validate the current state.
 *
 * @since 1.19.0
 *
 * @param {Function} validate         Validation function callback.
 * @param {Object}   [options]        Options to modify the behavior of the generated selectors.
 * @param {boolean}  [options.negate] Whether to negate the boolean result or not. Default: false.
 * @return {Object} Safe and dangerous selectors.
 */
function createValidationSelector(validate, {
  negate = false
} = {}) {
  const safeSelector = (0,_wordpress_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, ...args) => {
    const pass = negate ? false : true;
    const fail = negate ? true : false;
    try {
      validate(select, state, ...args);
      return pass;
    } catch {
      return fail;
    }
  });
  const dangerousSelector = (0,_wordpress_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, ...args) => {
    validate(select, state, ...args);
  });
  return {
    safeSelector,
    dangerousSelector
  };
}

/**
 * Creates a validated action creator.
 *
 * @since 1.32.0
 *
 * @param {Function} validate      A function for validating action arguments.
 * @param {Function} actionCreator A function for returning or yielding redux-style actions.
 * @return {Function} An enhanced action creator.
 */
function createValidatedAction(validate, actionCreator) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof validate === 'function', 'a validator function is required.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof actionCreator === 'function', 'an action creator function is required.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(validate[Symbol.toStringTag] !== 'Generator' && validate[Symbol.toStringTag] !== 'GeneratorFunction', 'an action’s validator function must not be a generator.');
  return (...args) => {
    validate(...args);
    return actionCreator(...args);
  };
}

/***/ }),

/***/ "./js/googlesitekit/datastore/site/constants.js":
/*!******************************************************!*\
  !*** ./js/googlesitekit/datastore/site/constants.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AMP_MODE_PRIMARY: () => (/* binding */ AMP_MODE_PRIMARY),
/* harmony export */   AMP_MODE_SECONDARY: () => (/* binding */ AMP_MODE_SECONDARY),
/* harmony export */   CORE_SITE: () => (/* binding */ CORE_SITE)
/* harmony export */ });
/**
 * `core/site` data store: constants.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const CORE_SITE = 'core/site';
const AMP_MODE_PRIMARY = 'primary';
const AMP_MODE_SECONDARY = 'secondary';

/***/ }),

/***/ "./js/googlesitekit/datastore/user/adblocker.js":
/*!******************************************************!*\
  !*** ./js/googlesitekit/datastore/user/adblocker.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var just_detect_adblock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! just-detect-adblock */ "../node_modules/just-detect-adblock/dist/bundle.umd.js");
/* harmony import */ var just_detect_adblock__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(just_detect_adblock__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/**
 * `core/user` data store: adblocker.
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */



// Actions
const CHECK_ADBLOCKER = 'CHECK_ADBLOCKER';
const RECEIVE_IS_ADBLOCKER_ACTIVE = 'RECEIVE_IS_ADBLOCKER_ACTIVE';
const initialState = {
  isAdBlockerActive: undefined
};
const actions = {
  *checkAdBlocker() {
    return yield {
      payload: {},
      type: CHECK_ADBLOCKER
    };
  },
  receiveIsAdBlockerActive(isAdBlockerActive) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('boolean' === typeof isAdBlockerActive, 'isAdBlockerActive must be boolean.');
    return {
      payload: {
        isAdBlockerActive
      },
      type: RECEIVE_IS_ADBLOCKER_ACTIVE
    };
  }
};
const controls = {
  [CHECK_ADBLOCKER]: async () => {
    if (await (0,just_detect_adblock__WEBPACK_IMPORTED_MODULE_1__.detectAnyAdblocker)()) {
      return true;
    }

    // The above is good about detecting most adblockers.
    // For the rest, we'll make a placeholder request to the favicon with some
    // additional stuff in the query string to (hopefully) trigger a filter.
    // If this throws, then the fetch request failed completely and we'll assume it was blocked.
    try {
      const params = [
      // The name of the parameter here doesn't really matter
      // since adblockers look at the URL as a whole.
      // Note: this value must not be URL-encoded.
      'google-site-kit=/adsense/pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
      // Add a timestamp for cache-busting.
      //
      // This value is used for cache-busting, so we don't want
      // to rely on the reference date. We should always use
      // the current time.
      `timestamp=${Date.now()}` // eslint-disable-line sitekit/no-direct-date
      ];
      await fetch(`/favicon.ico?${params.join('&')}`, {
        credentials: 'omit',
        // Don't follow any redirects; we only care about this request being blocked or not.
        redirect: 'manual'
      });
    } catch {
      return true;
    }
    return false;
  }
};
const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, {
  payload,
  type
}) => {
  switch (type) {
    case RECEIVE_IS_ADBLOCKER_ACTIVE:
      state.isAdBlockerActive = payload.isAdBlockerActive;
      break;
    default:
      break;
  }
});
const resolvers = {
  *isAdBlockerActive() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
    const isAdBlockerActive = registry.select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).isAdBlockerActive();

    // If the ad blocker status is already set, don't make any requests
    // to check the ad blocker status.
    if (undefined !== isAdBlockerActive) {
      return;
    }
    const detected = yield actions.checkAdBlocker();
    yield actions.receiveIsAdBlockerActive(detected);
  }
};
const selectors = {
  /**
   * Returns whether an ad blocker is active on the client.
   *
   * @since 1.9.0
   * @since 1.125.0 Selector moved from the `MODULES_ADSENSE` store to the `CORE_USER` store.
   *
   * @param {Object} state Data store's state.
   * @return {boolean|undefined} True or false depending on whether an ad blocker is active; `undefined` if not loaded.
   */
  isAdBlockerActive(state) {
    const {
      isAdBlockerActive
    } = state;
    return isAdBlockerActive;
  }
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  initialState,
  actions,
  controls,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/audience-settings.js":
/*!**************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/audience-settings.js ***!
  \**************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/modules/analytics-4/datastore/constants */ "./js/modules/analytics-4/datastore/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/* harmony import */ var _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/js/googlesitekit/data/create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/**
 * `core/user` data store: audience settings.
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable sitekit/jsdoc-no-unnamed-boolean-params */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */







const {
  receiveError,
  clearError
} = _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_7__.actions;
function validateUserAudienceSettings(settings) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Audience settings should be an object.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(Array.isArray(settings.configuredAudiences), 'Configured audiences should be an array.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof settings.isAudienceSegmentationWidgetHidden === 'boolean', 'Audience segmentation widget visibility should be a boolean.');
}
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, audienceSettings) => {
  if (!state.audienceSettings) {
    state.audienceSettings = {};
  }
  state.audienceSettings.settings = audienceSettings;
  state.audienceSettings.savedSettings = audienceSettings;
});
const fetchGetUserAudienceSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getUserAudienceSettings',
  controlCallback() {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'audience-settings', {}, {
      useCache: false
    });
  },
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveUserAudienceSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'saveUserAudienceSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'audience-settings', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: validateUserAudienceSettings
});

// Actions
const RESET_AUDIENCE_SETTINGS = 'RESET_AUDIENCE_SETTINGS';
const SET_CONFIGURED_AUDIENCES = 'SET_CONFIGURED_AUDIENCES';
const SET_AUDIENCE_SEGMENTATION_WIDGET_HIDDEN = 'SET_AUDIENCE_SEGMENTATION_WIDGET_HIDDEN';
const baseInitialState = {
  audienceSettings: undefined
};
const baseActions = {
  /**
   * Saves the audience settings.
   *
   * @since 1.124.0
   *
   * @param {Object} settings Optional. By default, this saves whatever there is in the store. Use this object to save additional settings.
   * @return {Object} Object with `response` and `error`.
   */
  saveUserAudienceSettings: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((settings = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'audience settings should be an object to save.');
  }, function* (settings = {}) {
    yield clearError('saveUserAudienceSettings', []);
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const audienceSettings = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(registry.resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).getUserAudienceSettings());
    const finalSettings = {
      ...audienceSettings,
      ...settings
    };
    const availableAudiences = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(registry.resolveSelect(_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_4__.MODULES_ANALYTICS_4).getOrSyncAvailableAudiences());
    const sortedConfiguredAudiences = [...finalSettings.configuredAudiences].sort((audienceNameA, audienceNameB) => {
      const audienceIndexA = availableAudiences.findIndex(audience => audience.name === audienceNameA);
      const audienceIndexB = availableAudiences.findIndex(audience => audience.name === audienceNameB);
      if (audienceIndexA === -1 || audienceIndexB === -1) {
        return 0;
      }
      return audienceIndexA - audienceIndexB;
    });
    finalSettings.configuredAudiences = sortedConfiguredAudiences;
    const {
      response,
      error
    } = yield fetchSaveUserAudienceSettingsStore.actions.fetchSaveUserAudienceSettings(finalSettings);
    if (error) {
      yield receiveError(error, 'saveUserAudienceSettings', []);
    }
    return {
      response,
      error
    };
  }),
  /**
   * Resets the audience settings.
   *
   * @since 1.139.0
   *
   * @return {Object} Redux-style action.
   */
  *resetUserAudienceSettings() {
    const {
      dispatch
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    yield {
      payload: {},
      type: RESET_AUDIENCE_SETTINGS
    };
    yield _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_7__.actions.clearErrors('getUserAudienceSettings');
    return dispatch(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).invalidateResolutionForStoreSelector('getUserAudienceSettings');
  },
  /**
   * Sets the configured audiences.
   *
   * @since 1.124.0
   *
   * @param {Array} audienceResourceNames Configured audience resource names.
   * @return {Object} Redux-style action.
   */
  setConfiguredAudiences(audienceResourceNames) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Array.isArray(audienceResourceNames), 'Configured audiences should be an array.');
    return {
      type: SET_CONFIGURED_AUDIENCES,
      payload: {
        audienceResourceNames
      }
    };
  },
  /**
   * Sets the audience segmentation widget visibility.
   *
   * @since 1.124.0
   *
   * @param {boolean} isWidgetHidden Whether or not the audience segmentation widget is hidden.
   * @return {Object} Redux-style action.
   */
  setAudienceSegmentationWidgetHidden(isWidgetHidden) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof isWidgetHidden === 'boolean', 'Audience segmentation widget visibility should be a boolean.');
    return {
      type: SET_AUDIENCE_SEGMENTATION_WIDGET_HIDDEN,
      payload: {
        isWidgetHidden
      }
    };
  }
};
const baseControls = {};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case RESET_AUDIENCE_SETTINGS:
      {
        state.audienceSettings = baseInitialState.audienceSettings;
        break;
      }
    case SET_CONFIGURED_AUDIENCES:
      {
        const {
          audienceResourceNames
        } = payload;
        if (!state.audienceSettings) {
          state.audienceSettings = {};
        }
        state.audienceSettings.settings = {
          ...state.audienceSettings.settings,
          configuredAudiences: audienceResourceNames
        };
        break;
      }
    case SET_AUDIENCE_SEGMENTATION_WIDGET_HIDDEN:
      {
        const {
          isWidgetHidden
        } = payload;
        if (!state.audienceSettings) {
          state.audienceSettings = {};
        }
        state.audienceSettings.settings = {
          ...state.audienceSettings.settings,
          isAudienceSegmentationWidgetHidden: isWidgetHidden
        };
        break;
      }
    default:
      {
        break;
      }
  }
});
const baseResolvers = {
  *getUserAudienceSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const audienceSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).getUserAudienceSettings();
    if (audienceSettings === undefined) {
      yield fetchGetUserAudienceSettingsStore.actions.fetchGetUserAudienceSettings();
    }
  }
};
const baseSelectors = {
  /**
   * Gets the audience settings.
   *
   * @since 1.124.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Audience settings; `undefined` if not loaded.
   */
  getUserAudienceSettings(state) {
    return state.audienceSettings?.settings;
  },
  /**
   * Gets the configured audiences from the audience settings.
   *
   * @since 1.124.0
   *
   * @param {Object} state Data store's state.
   * @return {(Array|undefined)} An array with configured audiences; `undefined` if not loaded.
   */
  getConfiguredAudiences: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const audienceSettings = select(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).getUserAudienceSettings();
    return audienceSettings?.configuredAudiences;
  }),
  /**
   * Gets the audience segmentation widget visibility from the audience settings.
   *
   * @since 1.124.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} Whether or not the audience segmentation widget is hidden; `undefined` if not loaded.
   */
  isAudienceSegmentationWidgetHidden: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const audienceSettings = select(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).getUserAudienceSettings();
    return audienceSettings?.isAudienceSegmentationWidgetHidden;
  }),
  /**
   * Gets the `didSetAudiences` flag from the audience settings.
   *
   * @since 1.136.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} Whether or not the audience selection has ever been populated for the current user; `undefined` if not loaded.
   */
  didSetAudiences: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const audienceSettings = select(_constants__WEBPACK_IMPORTED_MODULE_8__.CORE_USER).getUserAudienceSettings();
    return audienceSettings?.didSetAudiences;
  }),
  /**
   * Checks if the configured audiences have changed from the saved settings.
   *
   * @since 1.124.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} True if configured audiences have changed, otherwise false.
   */
  haveConfiguredAudiencesChanged(state) {
    const {
      settings,
      savedSettings
    } = state.audienceSettings || {};
    return !(0,lodash__WEBPACK_IMPORTED_MODULE_1__.isEqual)(settings?.configuredAudiences, savedSettings?.configuredAudiences);
  },
  /**
   * Determines whether the audience settings are being saved.
   *
   * @since 1.129.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the audience settings are being saved, otherwise FALSE.
   */
  isSavingUserAudienceSettings(state) {
    // Since `isFetchingSaveUserAudienceSettings` holds information based on specific
    // values but we only need generic information here, we need to check
    // whether ANY such request is in progress.
    return Object.values(state.isFetchingSaveUserAudienceSettings).some(Boolean);
  }
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetUserAudienceSettingsStore, fetchSaveUserAudienceSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  controls: baseControls,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/authentication.js":
/*!***********************************************************!*\
  !*** ./js/googlesitekit/datastore/user/authentication.js ***!
  \***********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   baseReducer: () => (/* binding */ baseReducer),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/**
 * `core/user` data store: Authentication info.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */




function createGetAuthenticationSelector(property) {
  return (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const data = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getAuthentication() || {};
    return data[property];
  });
}
const fetchGetAuthenticationStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
  baseName: 'getAuthentication',
  controlCallback: () => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__.get)('core', 'user', 'authentication', undefined, {
      useCache: false
    });
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, authentication) => {
    state.authentication = authentication;
  })
});

// Actions
const SET_AUTH_ERROR = 'SET_AUTH_ERROR';
const CLEAR_AUTH_ERROR = 'CLEAR_AUTH_ERROR';
const baseInitialState = {
  authentication: undefined,
  authError: null
};
const baseActions = {
  /**
   * Sets the authentication error.
   *
   * @since 1.18.0
   *
   * @param {Object} error Authentication error object.
   * @return {Object} Redux-style action.
   */
  setAuthError(error) {
    return {
      payload: {
        error
      },
      type: SET_AUTH_ERROR
    };
  },
  /**
   * Clears the authentication error, if one was previously set.
   *
   * @since 1.18.0
   *
   * @return {Object} Redux-style action.
   */
  clearAuthError() {
    return {
      payload: {},
      type: CLEAR_AUTH_ERROR
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case SET_AUTH_ERROR:
      state.authError = payload.error;
      break;
    case CLEAR_AUTH_ERROR:
      state.authError = null;
      break;
    default:
      break;
  }
});
const baseResolvers = {
  *getAuthentication() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (!select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getAuthentication()) {
      yield fetchGetAuthenticationStore.actions.fetchGetAuthentication();
    }
  }
};
const baseSelectors = {
  /**
   * Gets the authentication info for this user.
   *
   * Returns `undefined` if the authentication info is not available/loaded.
   *
   * Returns an object with the shape when successful:
   * ```
   * {
   *   authenticated: <Boolean>,
   *   grantedScopes: <Array>,
   *   requiredScopes: <Array>
   * }
   * ```
   *
   * @since 1.9.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} User authentication info.
   */
  getAuthentication(state) {
    const {
      authentication
    } = state;
    return authentication;
  },
  /**
   * Checks to see if the current user has granted a particular scope.
   *
   * Returns `undefined` if the scope info is not available/loaded.
   *
   * @since 1.11.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @param {string} scope The scope constant to check for.
   * @return {(boolean|undefined)} `true` if scope is present; `false` if not.
   */
  hasScope: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => (state, scope) => {
    const grantedScopes = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getGrantedScopes(state);
    if (grantedScopes === undefined) {
      return undefined;
    }
    return grantedScopes.includes(scope);
  }),
  /**
   * Gets the Site Kit authentication status for this user.
   *
   * Returns `true` if the user is authenticated, `false` if
   * not. Returns `undefined` if the authentication info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} User authentication status.
   */
  isAuthenticated: createGetAuthenticationSelector('authenticated'),
  /**
   * Gets the granted scopes for the user.
   *
   * Returns an array of granted scopes or undefined
   * if authentication info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(Array|undefined)} Array of granted scopes.
   */
  getGrantedScopes: createGetAuthenticationSelector('grantedScopes'),
  /**
   * Gets the required scopes for the user.
   *
   * Returns an array of required scopes or undefined
   * if authentication info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(Array|undefined)} Array of required scopes.
   */
  getRequiredScopes: createGetAuthenticationSelector('requiredScopes'),
  /**
   * Gets the unsatisfied scopes for the user.
   *
   * Returns an array of unsatisfied scopes (required but not granted)
   * or undefined if authentication info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(Array|undefined)} Array of scopes.
   */
  getUnsatisfiedScopes: createGetAuthenticationSelector('unsatisfiedScopes'),
  /**
   * Checks reauthentication status for this user.
   *
   * Returns true if any required scopes are not satisfied or undefined
   * if reauthentication info is not available/loaded.
   *
   * @since 1.10.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} User reauthentication status.
   */
  needsReauthentication: createGetAuthenticationSelector('needsReauthentication'),
  /**
   * Gets the current disconnected reason.
   *
   * @since 1.17.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The current disconnected reason.
   */
  getDisconnectedReason: createGetAuthenticationSelector('disconnectedReason'),
  /**
   * Gets the connected proxy URL.
   *
   * @since 1.48.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The current connected proxy URL.
   */
  getConnectedProxyURL: createGetAuthenticationSelector('connectedProxyURL'),
  /**
   * Gets the previous connected proxy URL.
   *
   * @since 1.48.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The previous connected proxy URL.
   */
  getPreviousConnectedProxyURL: createGetAuthenticationSelector('previousConnectedProxyURL'),
  /**
   * Gets the authentication error.
   *
   * @since 1.18.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|null)} Authentication error object if available, otherwise null.
   */
  getAuthError(state) {
    const {
      authError
    } = state;
    return authError;
  }
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.combineStores)(fetchGetAuthenticationStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/constants.js":
/*!******************************************************!*\
  !*** ./js/googlesitekit/datastore/user/constants.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CORE_USER: () => (/* binding */ CORE_USER),
/* harmony export */   DISCONNECTED_REASON_CONNECTED_URL_MISMATCH: () => (/* binding */ DISCONNECTED_REASON_CONNECTED_URL_MISMATCH),
/* harmony export */   EMAIL_REPORT_FREQUENCIES: () => (/* binding */ EMAIL_REPORT_FREQUENCIES),
/* harmony export */   ERROR_CODE_ADBLOCKER_ACTIVE: () => (/* binding */ ERROR_CODE_ADBLOCKER_ACTIVE),
/* harmony export */   FORM_TEMPORARY_PERSIST_PERMISSION_ERROR: () => (/* binding */ FORM_TEMPORARY_PERSIST_PERMISSION_ERROR),
/* harmony export */   GLOBAL_SURVEYS_TIMEOUT_SLUG: () => (/* binding */ GLOBAL_SURVEYS_TIMEOUT_SLUG),
/* harmony export */   KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT: () => (/* binding */ KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT),
/* harmony export */   KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE: () => (/* binding */ KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE),
/* harmony export */   KM_ANALYTICS_LEAST_ENGAGING_PAGES: () => (/* binding */ KM_ANALYTICS_LEAST_ENGAGING_PAGES),
/* harmony export */   KM_ANALYTICS_MOST_ENGAGING_PAGES: () => (/* binding */ KM_ANALYTICS_MOST_ENGAGING_PAGES),
/* harmony export */   KM_ANALYTICS_NEW_VISITORS: () => (/* binding */ KM_ANALYTICS_NEW_VISITORS),
/* harmony export */   KM_ANALYTICS_PAGES_PER_VISIT: () => (/* binding */ KM_ANALYTICS_PAGES_PER_VISIT),
/* harmony export */   KM_ANALYTICS_POPULAR_AUTHORS: () => (/* binding */ KM_ANALYTICS_POPULAR_AUTHORS),
/* harmony export */   KM_ANALYTICS_POPULAR_CONTENT: () => (/* binding */ KM_ANALYTICS_POPULAR_CONTENT),
/* harmony export */   KM_ANALYTICS_POPULAR_PRODUCTS: () => (/* binding */ KM_ANALYTICS_POPULAR_PRODUCTS),
/* harmony export */   KM_ANALYTICS_RETURNING_VISITORS: () => (/* binding */ KM_ANALYTICS_RETURNING_VISITORS),
/* harmony export */   KM_ANALYTICS_TOP_CATEGORIES: () => (/* binding */ KM_ANALYTICS_TOP_CATEGORIES),
/* harmony export */   KM_ANALYTICS_TOP_CITIES: () => (/* binding */ KM_ANALYTICS_TOP_CITIES),
/* harmony export */   KM_ANALYTICS_TOP_CITIES_DRIVING_ADD_TO_CART: () => (/* binding */ KM_ANALYTICS_TOP_CITIES_DRIVING_ADD_TO_CART),
/* harmony export */   KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS: () => (/* binding */ KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS),
/* harmony export */   KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES: () => (/* binding */ KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES),
/* harmony export */   KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE: () => (/* binding */ KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE),
/* harmony export */   KM_ANALYTICS_TOP_COUNTRIES: () => (/* binding */ KM_ANALYTICS_TOP_COUNTRIES),
/* harmony export */   KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES: () => (/* binding */ KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES),
/* harmony export */   KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS: () => (/* binding */ KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS),
/* harmony export */   KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES: () => (/* binding */ KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES),
/* harmony export */   KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES: () => (/* binding */ KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES),
/* harmony export */   KM_ANALYTICS_TOP_TRAFFIC_SOURCE: () => (/* binding */ KM_ANALYTICS_TOP_TRAFFIC_SOURCE),
/* harmony export */   KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART: () => (/* binding */ KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART),
/* harmony export */   KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS: () => (/* binding */ KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS),
/* harmony export */   KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES: () => (/* binding */ KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES),
/* harmony export */   KM_ANALYTICS_VISITS_PER_VISITOR: () => (/* binding */ KM_ANALYTICS_VISITS_PER_VISITOR),
/* harmony export */   KM_ANALYTICS_VISIT_LENGTH: () => (/* binding */ KM_ANALYTICS_VISIT_LENGTH),
/* harmony export */   KM_SEARCH_CONSOLE_POPULAR_KEYWORDS: () => (/* binding */ KM_SEARCH_CONSOLE_POPULAR_KEYWORDS),
/* harmony export */   PERMISSION_AUTHENTICATE: () => (/* binding */ PERMISSION_AUTHENTICATE),
/* harmony export */   PERMISSION_DELEGATE_MODULE_SHARING_MANAGEMENT: () => (/* binding */ PERMISSION_DELEGATE_MODULE_SHARING_MANAGEMENT),
/* harmony export */   PERMISSION_MANAGE_MODULE_SHARING_OPTIONS: () => (/* binding */ PERMISSION_MANAGE_MODULE_SHARING_OPTIONS),
/* harmony export */   PERMISSION_MANAGE_OPTIONS: () => (/* binding */ PERMISSION_MANAGE_OPTIONS),
/* harmony export */   PERMISSION_READ_SHARED_MODULE_DATA: () => (/* binding */ PERMISSION_READ_SHARED_MODULE_DATA),
/* harmony export */   PERMISSION_SETUP: () => (/* binding */ PERMISSION_SETUP),
/* harmony export */   PERMISSION_UPDATE_PLUGINS: () => (/* binding */ PERMISSION_UPDATE_PLUGINS),
/* harmony export */   PERMISSION_VIEW_DASHBOARD: () => (/* binding */ PERMISSION_VIEW_DASHBOARD),
/* harmony export */   PERMISSION_VIEW_MODULE_DETAILS: () => (/* binding */ PERMISSION_VIEW_MODULE_DETAILS),
/* harmony export */   PERMISSION_VIEW_POSTS_INSIGHTS: () => (/* binding */ PERMISSION_VIEW_POSTS_INSIGHTS),
/* harmony export */   PERMISSION_VIEW_SHARED_DASHBOARD: () => (/* binding */ PERMISSION_VIEW_SHARED_DASHBOARD),
/* harmony export */   allKeyMetricsTileWidgets: () => (/* binding */ allKeyMetricsTileWidgets),
/* harmony export */   keyMetricsGA4Widgets: () => (/* binding */ keyMetricsGA4Widgets)
/* harmony export */ });
/**
 * `core/user` data store: constants.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const CORE_USER = 'core/user';
const DISCONNECTED_REASON_CONNECTED_URL_MISMATCH = 'connected_url_mismatch';
const GLOBAL_SURVEYS_TIMEOUT_SLUG = '__global';
const FORM_TEMPORARY_PERSIST_PERMISSION_ERROR = 'temporary_persist_permission_error';
const ERROR_CODE_ADBLOCKER_ACTIVE = 'adblocker_active';

// Email Report Frequency options.
const EMAIL_REPORT_FREQUENCIES = ['weekly', 'monthly', 'quarterly'];

// Permissions list.
const PERMISSION_AUTHENTICATE = 'googlesitekit_authenticate';
const PERMISSION_SETUP = 'googlesitekit_setup';
const PERMISSION_VIEW_POSTS_INSIGHTS = 'googlesitekit_view_posts_insights';
const PERMISSION_VIEW_DASHBOARD = 'googlesitekit_view_dashboard';
const PERMISSION_VIEW_SHARED_DASHBOARD = 'googlesitekit_view_shared_dashboard';
const PERMISSION_VIEW_MODULE_DETAILS = 'googlesitekit_view_module_details';
const PERMISSION_MANAGE_OPTIONS = 'googlesitekit_manage_options';
const PERMISSION_READ_SHARED_MODULE_DATA = 'googlesitekit_read_shared_module_data';
const PERMISSION_MANAGE_MODULE_SHARING_OPTIONS = 'googlesitekit_manage_module_sharing_options';
const PERMISSION_DELEGATE_MODULE_SHARING_MANAGEMENT = 'googlesitekit_delegate_module_sharing_management';
const PERMISSION_UPDATE_PLUGINS = 'googlesitekit_update_plugins';

// Key Metrics Widgets
const KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT = 'kmAnalyticsAdSenseTopEarningContent';
const KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE = 'kmAnalyticsEngagedTrafficSource';
const KM_ANALYTICS_LEAST_ENGAGING_PAGES = 'kmAnalyticsLeastEngagingPages';
const KM_ANALYTICS_NEW_VISITORS = 'kmAnalyticsNewVisitors';
const KM_ANALYTICS_POPULAR_AUTHORS = 'kmAnalyticsPopularAuthors';
const KM_ANALYTICS_POPULAR_CONTENT = 'kmAnalyticsPopularContent';
const KM_ANALYTICS_POPULAR_PRODUCTS = 'kmAnalyticsPopularProducts';
const KM_ANALYTICS_RETURNING_VISITORS = 'kmAnalyticsReturningVisitors';
const KM_ANALYTICS_TOP_CITIES = 'kmAnalyticsTopCities';
const KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS = 'kmAnalyticsTopCitiesDrivingLeads';
const KM_ANALYTICS_TOP_CITIES_DRIVING_ADD_TO_CART = 'kmAnalyticsTopCitiesDrivingAddToCart';
const KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES = 'kmAnalyticsTopCitiesDrivingPurchases';
const KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES = 'kmAnalyticsTopDeviceDrivingPurchases';
const KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE = 'kmAnalyticsTopConvertingTrafficSource';
const KM_ANALYTICS_TOP_COUNTRIES = 'kmAnalyticsTopCountries';
const KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS = 'kmAnalyticsTopPagesDrivingLeads';
const KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES = 'kmAnalyticsTopRecentTrendingPages';
const KM_ANALYTICS_TOP_TRAFFIC_SOURCE = 'kmAnalyticsTopTrafficSource';
const KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART = 'kmAnalyticsTopTrafficSourceDrivingAddToCart';
const KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS = 'kmAnalyticsTopTrafficSourceDrivingLeads';
const KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES = 'kmAnalyticsTopTrafficSourceDrivingPurchases';
const KM_ANALYTICS_PAGES_PER_VISIT = 'kmAnalyticsPagesPerVisit';
const KM_ANALYTICS_VISIT_LENGTH = 'kmAnalyticsVisitLength';
const KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES = 'kmAnalyticsTopReturningVisitorPages';
const KM_SEARCH_CONSOLE_POPULAR_KEYWORDS = 'kmSearchConsolePopularKeywords';
const KM_ANALYTICS_VISITS_PER_VISITOR = 'kmAnalyticsVisitsPerVisitor';
const KM_ANALYTICS_MOST_ENGAGING_PAGES = 'kmAnalyticsMostEngagingPages';
const KM_ANALYTICS_TOP_CATEGORIES = 'kmAnalyticsTopCategories';
const keyMetricsGA4Widgets = [KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT, KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, KM_ANALYTICS_LEAST_ENGAGING_PAGES, KM_ANALYTICS_NEW_VISITORS, KM_ANALYTICS_POPULAR_AUTHORS, KM_ANALYTICS_POPULAR_CONTENT, KM_ANALYTICS_POPULAR_PRODUCTS, KM_ANALYTICS_RETURNING_VISITORS, KM_ANALYTICS_TOP_CATEGORIES, KM_ANALYTICS_TOP_CITIES, KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS, KM_ANALYTICS_TOP_CITIES_DRIVING_ADD_TO_CART, KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES, KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES, KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE, KM_ANALYTICS_TOP_COUNTRIES, KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES, KM_ANALYTICS_TOP_TRAFFIC_SOURCE, KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART, KM_ANALYTICS_PAGES_PER_VISIT, KM_ANALYTICS_VISIT_LENGTH, KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES, KM_ANALYTICS_VISITS_PER_VISITOR, KM_ANALYTICS_MOST_ENGAGING_PAGES, KM_ANALYTICS_TOP_CATEGORIES];
const allKeyMetricsTileWidgets = [...keyMetricsGA4Widgets, KM_SEARCH_CONSOLE_POPULAR_KEYWORDS];

/***/ }),

/***/ "./js/googlesitekit/datastore/user/conversion-reporting-settings.js":
/*!**************************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/conversion-reporting-settings.js ***!
  \**************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */





const baseInitialState = {
  conversionReportingSettings: undefined
};
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, conversionReportingSettings) => {
  state.conversionReportingSettings = conversionReportingSettings;
});
const fetchGetConversionReportingSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getConversionReportingSettings',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'conversion-reporting-settings', undefined, {
    // Never cache conversion reporting settings requests, we want them to be
    // up-to-date with what's in settings, and they don't
    // make requests to Google APIs so it's not a slow request.
    useCache: false
  }),
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveConversionReportingSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'saveConversionReportingSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'conversion-reporting-settings', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: settings => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Conversion reporting settings should be an object.');
    if (settings.newEventsCalloutDismissedAt) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(settings.newEventsCalloutDismissedAt), 'newEventsCalloutDismissedAt should be a timestamp.');
    }
    if (settings.lostEventsCalloutDismissedAt) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(settings.lostEventsCalloutDismissedAt), 'lostEventsCalloutDismissedAt should be an integer.');
    }
  }
});
const baseActions = {
  /**
   * Saves the conversion reporting settings.
   *
   * @since 1.144.0
   *
   * @param {Object} settings Optional. By default, this saves whatever there is in the store. Use this object to save additional settings.
   * @return {Object} Object with `response` and `error`.
   */
  saveConversionReportingSettings: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((settings = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Conversion reporting settings should be an object to save.');
  }, function* (settings = {}) {
    return yield fetchSaveConversionReportingSettingsStore.actions.fetchSaveConversionReportingSettings(settings);
  })
};
const baseResolvers = {
  *getConversionReportingSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const conversionReportingSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getConversionReportingSettings();
    if (conversionReportingSettings === undefined) {
      yield fetchGetConversionReportingSettingsStore.actions.fetchGetConversionReportingSettings();
    }
  }
};
const baseSelectors = {
  /**
   * Gets the conversion reporting settings.
   *
   * @since 1.144.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Conversion reporting settings; `undefined` if not loaded.
   */
  getConversionReportingSettings(state) {
    return state.conversionReportingSettings;
  },
  /**
   * Determines whether the conversion reporting settings are being saved or not.
   *
   * @since 1.144.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the key metrics settings are being saved, otherwise FALSE.
   */
  isSavingConversionReportingSettings(state) {
    // Since isFetchingSaveConversionReportingSettings holds information based on specific values but we only need
    // generic information here, we need to check whether ANY such request is in progress.
    return Object.values(state.isFetchingSaveConversionReportingSettings).some(Boolean);
  },
  /**
   * Determines whether the new events callout should be shown or not.
   *
   * @since 1.144.0
   *
   * @return {boolean} TRUE if the there were new events detected after the callout was dismissed, otherwise FALSE.
   */
  haveNewConversionEventsAfterDismiss: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, newEventsLastSyncedAt) => {
    const {
      getConversionReportingSettings
    } = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER);
    const conversionReportingSettings = getConversionReportingSettings();
    if (!conversionReportingSettings) {
      return false;
    }
    if (newEventsLastSyncedAt > conversionReportingSettings.newEventsCalloutDismissedAt) {
      return true;
    }
    return false;
  }),
  /**
   * Determines whether the lost events callout should be shown or not.
   *
   * @since 1.144.0
   *
   * @return {boolean} TRUE if the there were lost events detected after the callout was dismissed, otherwise FALSE.
   */
  haveLostConversionEventsAfterDismiss: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, lostEventsLastSyncedAt) => {
    const {
      getConversionReportingSettings
    } = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER);
    const conversionReportingSettings = getConversionReportingSettings();
    if (!conversionReportingSettings) {
      return false;
    }
    if (lostEventsLastSyncedAt > conversionReportingSettings.lostEventsCalloutDismissedAt) {
      return true;
    }
    return false;
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetConversionReportingSettingsStore, fetchSaveConversionReportingSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/date-range.js":
/*!*******************************************************!*\
  !*** ./js/googlesitekit/datastore/user/date-range.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _js_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/js/util */ "./js/util/index.js");
/**
 * `core/user` data store: date-range.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */


const initialState = {
  dateRange: 'last-28-days',
  // This is where we actually _set_ the reference date (which should
  // have a default value of the current date).
  //
  // Using `new Date()` here is appropriate.
  referenceDate: (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.getDateString)(new Date()) // eslint-disable-line sitekit/no-direct-date
};

/**
 * Date Range Object.
 *
 * @since 1.18.0
 *
 * @typedef {Object} DateRangeReturnObj
 * @property {string} startDate          Beginning of the original date range.
 * @property {string} endDate            End of the original date range.
 * @property {string} [compareStartDate] Beginning of the comparative date range.
 * @property {string} [compareEndDate]   End of the comparative date range.
 */

// Actions
const SET_DATE_RANGE = 'SET_DATE_RANGE';
const SET_REFERENCE_DATE = 'SET_REFERENCE_DATE';
const actions = {
  /**
   * Sets a new date range.
   *
   * @since 1.12.0
   *
   * @param {string} slug Date range slug.
   * @return {Object} Redux-style action.
   */
  setDateRange(slug) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'Date range slug is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,_js_util__WEBPACK_IMPORTED_MODULE_2__.isValidDateRange)(slug), _js_util__WEBPACK_IMPORTED_MODULE_2__.INVALID_DATE_RANGE_ERROR);
    return {
      type: SET_DATE_RANGE,
      payload: {
        slug
      }
    };
  },
  /**
   * Sets the current reference date.
   *
   * This should only be used for testing, to enforce another reference date
   * than today.
   *
   * @since 1.22.0
   * @private
   *
   * @param {string} dateString Reference date string as YYYY-MM-DD.
   * @return {Object} Redux-style action.
   */
  setReferenceDate(dateString) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(dateString, 'Date string is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,_js_util__WEBPACK_IMPORTED_MODULE_2__.isValidDateString)(dateString), _js_util__WEBPACK_IMPORTED_MODULE_2__.INVALID_DATE_STRING_ERROR);
    return {
      type: SET_REFERENCE_DATE,
      payload: {
        dateString
      }
    };
  }
};
const controls = {};
const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case SET_DATE_RANGE:
      state.dateRange = payload.slug;
      break;
    case SET_REFERENCE_DATE:
      state.referenceDate = payload.dateString;
      break;
    default:
      break;
  }
});
const resolvers = {};
const selectors = {
  /**
   * Returns the current date range.
   *
   * @since 1.12.0
   *
   * @param {Object} state The current data store's state.
   * @return {string} The current date range slug.
   */
  getDateRange(state) {
    const {
      dateRange
    } = state;
    return dateRange;
  },
  /**
   * Returns the current date range as a list of date strings.
   *
   * @since 1.18.0
   *
   * @param {Object}  state                   The current data store's state.
   * @param {Object}  [options]               Options parameter. Default is: {}.
   * @param {boolean} [options.compare]       Set to true if date ranges to compare should be included. Default is: false.
   * @param {number}  [options.offsetDays]    Number of days to offset. Default is: 0.
   * @param {string}  [options.referenceDate] Used for testing to set a static date. Default is the datastore's reference date.
   * @return {DateRangeReturnObj}             Object containing dates for date ranges.
   */
  getDateRangeDates(state, {
    compare = false,
    offsetDays,
    referenceDate = state.referenceDate
  } = {}) {
    if (offsetDays === undefined) {
      __webpack_require__.g.console.warn('getDateRangeDates was called without offsetDays');
      offsetDays = 0;
    }
    const dateRange = selectors.getDateRange(state);
    const endDate = (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.getPreviousDate)(referenceDate, offsetDays);
    const matches = dateRange.match('-(.*)-');
    const numberOfDays = Number(matches ? matches[1] : 28);
    const startDate = (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.getPreviousDate)(endDate, numberOfDays - 1);
    const dates = {
      startDate,
      endDate
    };
    if (compare) {
      const compareEndDate = (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.getPreviousDate)(startDate, 1);
      const compareStartDate = (0,_js_util__WEBPACK_IMPORTED_MODULE_2__.getPreviousDate)(compareEndDate, numberOfDays - 1);
      dates.compareStartDate = compareStartDate;
      dates.compareEndDate = compareEndDate;
    }
    return dates;
  },
  /**
   * Returns the number of days in the current date range.
   *
   * @since 1.26.0
   *
   * @param {Object} state The current data store's state.
   * @return {number}      Integer. The number of days in the current date range.
   */
  getDateRangeNumberOfDays(state) {
    const dateRange = selectors.getDateRange(state);
    const matches = dateRange.match(/-(\d+)-/);
    return parseInt(matches ? matches[1] : 28, 10);
  },
  /**
   * Returns the current reference date, typically today.
   *
   * @since 1.22.0
   *
   * @param {Object} state The current data store's state.
   * @return {string} The current reference date as YYYY-MM-DD.
   */
  getReferenceDate(state) {
    return state.referenceDate;
  }
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  initialState,
  actions,
  controls,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/disconnect.js":
/*!*******************************************************!*\
  !*** ./js/googlesitekit/datastore/user/disconnect.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/**
 * `core/user` data store: disconnect
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */




const fetchDisconnectStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
  baseName: 'disconnect',
  controlCallback: () => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__.set)('core', 'user', 'disconnect');
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, disconnected) => {
    state.disconnected = disconnected;
  })
});
const baseInitialState = {
  disconnected: undefined
};
const baseActions = {
  *disconnect() {
    yield fetchDisconnectStore.actions.fetchDisconnect();
  }
};
const baseSelectors = {
  /**
   * Returns whether a disconnect is occurring.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} Is a disconnect occurring or not.
   */
  isDoingDisconnect: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    return select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).isFetchingDisconnect();
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.combineStores)(fetchDisconnectStore, {
  initialState: baseInitialState,
  actions: baseActions,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/dismissed-items.js":
/*!************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/dismissed-items.js ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * `core/user` data store: dismissed items
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */





const {
  getRegistry
} = googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions;
const reducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, dismissedItems) => {
  state.dismissedItems = Array.isArray(dismissedItems) ? dismissedItems : [];
});
const fetchGetDismissedItemsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'getDismissedItems',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.get)('core', 'user', 'dismissed-items', {}, {
    useCache: false
  }),
  reducerCallback
});
const fetchRemoveDismissedItemsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'removeDismissedItems',
  controlCallback: ({
    slugs
  }) => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.set)('core', 'user', 'dismissed-items', {
      slugs
    }, {
      method: 'DELETE'
    });
  },
  reducerCallback,
  argsToParams: slugs => {
    return {
      slugs
    };
  },
  validateParams: ({
    slugs
  }) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Array.isArray(slugs), 'slugs must be an array.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slugs.every(slug => typeof slug === 'string'), 'All slugs must be strings.');
  }
});
const fetchDismissItemStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'dismissItem',
  controlCallback: ({
    slug,
    expiresInSeconds
  }) => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.set)('core', 'user', 'dismiss-item', {
    slug,
    expiration: expiresInSeconds
  }),
  reducerCallback,
  argsToParams: (slug, expiresInSeconds = 0) => {
    return {
      slug,
      expiresInSeconds
    };
  },
  validateParams: ({
    slug,
    expiresInSeconds
  } = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'slug is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
  }
});
const baseInitialState = {
  dismissedItems: undefined,
  isDismissingItems: {}
};
const baseActions = {
  /**
   * Dismisses the given item by slug.
   *
   * @since 1.37.0
   *
   * @param {string} slug                       Item slug to dismiss.
   * @param {Object} options                    Dismiss item options.
   * @param {number} [options.expiresInSeconds] Optional. An integer number of seconds for expiry. 0 denotes permanent dismissal.
   * @return {Object} Generator instance.
   */
  dismissItem: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__.createValidatedAction)((slug, options = {}) => {
    const {
      expiresInSeconds = 0
    } = options;
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'A slug is required to dismiss an item.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof slug === 'string', 'A slug must be a string.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
  }, function* (slug, options = {}) {
    const {
      expiresInSeconds = 0
    } = options;
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
    registry.dispatch(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).setIsItemDimissing(slug, true);
    const {
      response,
      error
    } = yield fetchDismissItemStore.actions.fetchDismissItem(slug, expiresInSeconds);
    registry.dispatch(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).setIsItemDimissing(slug, false);
    return {
      response,
      error
    };
  }),
  /**
   * Removes dismissed items by their slugs.
   *
   * @since 1.133.0
   *
   * @param {...string} slugs Dismissed item slugs to remove.
   * @return {Object} Redux-style action.
   */
  removeDismissedItems: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__.createValidatedAction)((...slugs) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slugs.length > 0, 'At least one slug must be provided.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slugs.every(slug => typeof slug === 'string'), 'All slugs must be strings.');
  }, (...slugs) => {
    return fetchRemoveDismissedItemsStore.actions.fetchRemoveDismissedItems(slugs);
  }),
  setIsItemDimissing(slug, isDismissing) {
    return {
      payload: {
        slug,
        isDismissing
      },
      type: 'SET_IS_ITEM_DISMISSING'
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case 'SET_IS_ITEM_DISMISSING':
      {
        const {
          slug,
          isDismissing
        } = payload;
        state.isDismissingItems = {
          [slug]: isDismissing
        };
        break;
      }
    default:
      break;
  }
});
const baseResolvers = {
  *getDismissedItems() {
    const {
      select
    } = yield getRegistry();
    const dismissedItems = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getDismissedItems();
    if (dismissedItems === undefined) {
      yield fetchGetDismissedItemsStore.actions.fetchGetDismissedItems();
    }
  }
};
baseResolvers.isItemDismissed = baseResolvers.getDismissedItems;
const baseSelectors = {
  /**
   * Gets the list of dismissed items.
   *
   * @since 1.37.0
   *
   * @param {Object} state Data store's state.
   * @return {(string[]|undefined)} Array of dismissed item slugs, `undefined` if not resolved yet.
   */
  getDismissedItems(state) {
    return state.dismissedItems;
  },
  /**
   * Determines whether the item is dismissed or not.
   *
   * @since 1.37.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Item slug.
   * @return {(boolean|undefined)} TRUE if dismissed, otherwise FALSE, `undefined` if not resolved yet.
   */
  isItemDismissed: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, slug) => {
    return select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getDismissedItems()?.includes(slug);
  }),
  /**
   * Checks whether or not the item is being dismissed for the given slug.
   *
   * @since 1.48.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Item slug.
   * @return {(boolean|undefined)} True if the item is being dismissed, otherwise false.
   */
  isDismissingItem(state, slug) {
    return !!state.isDismissingItems[slug];
  }
};
const {
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
} = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.combineStores)({
  initialState: baseInitialState,
  actions: baseActions,
  resolvers: baseResolvers,
  reducer: baseReducer,
  selectors: baseSelectors
}, fetchDismissItemStore, fetchGetDismissedItemsStore, fetchRemoveDismissedItemsStore);
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/email-reporting-settings.js":
/*!*********************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/email-reporting-settings.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   baseReducer: () => (/* binding */ baseReducer),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * Site Kit by Google, Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */





const baseInitialState = {
  emailReporting: {
    settings: undefined,
    savedSettings: undefined,
    isSavingSettings: false
  }
};
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, emailReportingSettings) => {
  state.emailReporting.settings = emailReportingSettings;
  state.emailReporting.savedSettings = emailReportingSettings;
});
const fetchGetEmailReportingSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getEmailReportingSettings',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'email-reporting-settings', undefined, {
    useCache: false
  }),
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveEmailReportingSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'saveEmailReportingSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'email-reporting-settings', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: settings => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Email Reporting settings should be an object.');
    if (settings.subscribed !== undefined) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof settings.subscribed === 'boolean', 'subscribed should be a boolean.');
    }
    if (settings.frequency !== undefined) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof settings.frequency === 'string', 'frequency should be a string.');
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(_constants__WEBPACK_IMPORTED_MODULE_4__.EMAIL_REPORT_FREQUENCIES.includes(settings.frequency), `frequency should be one of: ${_constants__WEBPACK_IMPORTED_MODULE_4__.EMAIL_REPORT_FREQUENCIES.join(', ')}`);
    }
  }
});

// Actions
const SET_EMAIL_REPORTING_SETTINGS = 'SET_EMAIL_REPORTING_SETTINGS';
const SET_EMAIL_REPORTING_SETTINGS_SAVING_FLAG = 'SET_EMAIL_REPORTING_SETTINGS_SAVING_FLAG';
const RESET_EMAIL_REPORTING_SETTINGS = 'RESET_EMAIL_REPORTING_SETTINGS';
const baseActions = {
  /**
   * Sets email reporting settings.
   *
   * @since 1.162.0
   *
   * @param {Object} settings Settings object.
   * @return {Object} Redux-style action.
   */
  setEmailReportingSettings(settings) {
    return {
      type: SET_EMAIL_REPORTING_SETTINGS,
      payload: {
        settings
      }
    };
  },
  /**
   * Sets the email reporting frequency.
   *
   * @since 1.164.0
   *
   * @param {string} frequency Frequency value.
   * @return {Object} Redux-style action.
   */
  setEmailReportingFrequency(frequency) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(_constants__WEBPACK_IMPORTED_MODULE_4__.EMAIL_REPORT_FREQUENCIES.includes(frequency), `frequency should be one of: ${_constants__WEBPACK_IMPORTED_MODULE_4__.EMAIL_REPORT_FREQUENCIES.join(', ')}`);
    return {
      type: SET_EMAIL_REPORTING_SETTINGS,
      payload: {
        settings: {
          frequency
        }
      }
    };
  },
  /**
   * Saves the email reporting settings.
   *
   * @since 1.162.0
   *
   * @param {Object} settings Optional. By default, this saves whatever there is in the store. Use this object to save additional settings.
   * @return {Object} Object with `response` and `error`.
   */
  saveEmailReportingSettings: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((settings = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Email Reporting settings should be an object to save.');
  }, function* (settings = {}) {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();

    // Get current settings from state if no settings provided
    const currentSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getEmailReportingSettings();
    const defaultSettings = currentSettings || {};
    const settingsToSave = Object.keys(settings).length > 0 ? {
      ...defaultSettings,
      ...settings
    } : currentSettings;
    yield {
      type: SET_EMAIL_REPORTING_SETTINGS_SAVING_FLAG,
      payload: {
        isSaving: true
      }
    };
    const {
      response,
      error
    } = yield fetchSaveEmailReportingSettingsStore.actions.fetchSaveEmailReportingSettings(settingsToSave);
    yield {
      type: SET_EMAIL_REPORTING_SETTINGS_SAVING_FLAG,
      payload: {
        isSaving: false
      }
    };
    return {
      response,
      error
    };
  }),
  /**
   * Resets modified email reporting settings to currently saved values.
   *
   * @since 1.162.0
   *
   * @return {Object} Redux-style action.
   */
  *resetEmailReportingSettings() {
    return {
      type: RESET_EMAIL_REPORTING_SETTINGS,
      payload: {}
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, action) => {
  const {
    type,
    payload
  } = action;
  switch (type) {
    case SET_EMAIL_REPORTING_SETTINGS:
      {
        state.emailReporting.settings = {
          ...state.emailReporting.settings,
          ...payload.settings
        };
        break;
      }
    case SET_EMAIL_REPORTING_SETTINGS_SAVING_FLAG:
      {
        state.emailReporting.isSavingSettings = payload.isSaving;
        break;
      }
    case RESET_EMAIL_REPORTING_SETTINGS:
      {
        state.emailReporting.settings = state.emailReporting.savedSettings;
        break;
      }
    default:
      break;
  }
});
const baseResolvers = {
  *getEmailReportingSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const emailReportingSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getEmailReportingSettings();
    if (emailReportingSettings === undefined) {
      yield fetchGetEmailReportingSettingsStore.actions.fetchGetEmailReportingSettings();
    }
  }
};
const baseSelectors = {
  /**
   * Gets the email reporting settings.
   *
   * @since 1.162.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Email Reporting settings; `undefined` if not loaded.
   */
  getEmailReportingSettings(state) {
    return state.emailReporting.settings;
  },
  /**
   * Determines whether the user is subscribed to email reporting.
   *
   * @since 1.162.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the user is subscribed, otherwise FALSE.
   */
  isEmailReportingSubscribed(state) {
    const settings = state.emailReporting.settings;
    return !!settings?.subscribed;
  },
  /**
   * Determines whether the email reporting settings have changed from what is saved.
   *
   * @since 1.162.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the settings have changed, otherwise FALSE.
   */
  haveEmailReportingSettingsChanged(state) {
    const {
      settings,
      savedSettings
    } = state.emailReporting;
    return !(0,lodash__WEBPACK_IMPORTED_MODULE_1__.isEqual)(settings, savedSettings);
  },
  /**
   * Determines whether the email reporting settings are being saved or not.
   *
   * @since 1.162.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the settings are being saved, otherwise FALSE.
   */
  isSavingEmailReportingSettings(state) {
    return !!state.emailReporting.isSavingSettings;
  },
  /**
   * Gets the email reporting frequency.
   *
   * @since 1.164.0
   *
   * @param {Object} state Data store's state.
   * @return {string} Frequency value.
   */
  getEmailReportingFrequency(state) {
    const settings = state?.emailReporting?.settings;
    // If the settings haven't loaded at all, return `undefined` to signify
    // we're still loading this value.
    if (settings === undefined) {
      return undefined;
    }

    // Default to the first frequency option if settings have loaded
    // but the frequency is not set.
    return settings.frequency || _constants__WEBPACK_IMPORTED_MODULE_4__.EMAIL_REPORT_FREQUENCIES[0];
  },
  /**
   * Gets the previously-saved frequency.
   *
   * @since 1.164.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} Saved frequency or undefined.
   */
  getEmailReportingSavedFrequency(state) {
    return state?.emailReporting?.savedSettings?.frequency;
  }
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetEmailReportingSettingsStore, fetchSaveEmailReportingSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/expirable-items.js":
/*!************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/expirable-items.js ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * `core/user` data store: expirable items
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */





const {
  getRegistry
} = googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions;
const reducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, expirableItems) => {
  state.expirableItems = expirableItems;
});
const fetchGetExpirableItemsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'getExpirableItems',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.get)('core', 'user', 'expirable-items', {}, {
    useCache: false
  }),
  reducerCallback
});
const fetchSetExpirableItemTimersStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'setExpirableItemTimers',
  controlCallback: items => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.set)('core', 'user', 'set-expirable-item-timers', items),
  reducerCallback,
  argsToParams: (items = []) => {
    return items.map(item => {
      const {
        slug,
        expiresInSeconds
      } = item;
      return {
        slug,
        expiration: expiresInSeconds
      };
    });
  },
  validateParams: items => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Array.isArray(items), 'items are required.');
    items.forEach(item => {
      const {
        slug,
        expiresInSeconds = 0
      } = item;
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'slug is required.');
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
    });
  }
});
const baseInitialState = {
  expirableItems: undefined
};
const baseActions = {
  setExpirableItemTimers: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__.createValidatedAction)((items = []) => {
    items.forEach(item => {
      const {
        slug,
        expiresInSeconds
      } = item;
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'An item slug is required.');
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
    });
  }, items => {
    return fetchSetExpirableItemTimersStore.actions.fetchSetExpirableItemTimers(items);
  })
};
const baseResolvers = {
  *getExpirableItems() {
    const {
      select
    } = yield getRegistry();
    const expirableItems = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getExpirableItems();
    if (expirableItems === undefined) {
      yield fetchGetExpirableItemsStore.actions.fetchGetExpirableItems();
    }
  }
};
const baseSelectors = {
  /**
   * Returns the expirable items.
   *
   * @since 1.128.0
   *
   * @param {Object} state Data store's state.
   * @return {Array|undefined} Items if exists, `undefined` if not resolved yet.
   */
  getExpirableItems(state) {
    return state.expirableItems;
  },
  /**
   * Determines whether the item exists in expirable items.
   *
   * @since 1.128.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Item slug.
   * @return {(boolean|undefined)} TRUE if exists, otherwise FALSE, `undefined` if not resolved yet.
   */
  hasExpirableItem: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, slug) => {
    const expirableItems = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getExpirableItems();
    if (expirableItems === undefined) {
      return undefined;
    }
    return expirableItems.hasOwnProperty(slug);
  }),
  /**
   * Determines whether the item is active and not expired.
   *
   * @since 1.128.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Item slug.
   * @return {(boolean|undefined)} TRUE if exists, otherwise FALSE, `undefined` if not resolved yet.
   */
  isExpirableItemActive: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, slug) => {
    const expirableItems = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getExpirableItems();
    if (expirableItems === undefined) {
      return undefined;
    }
    const expiresInSeconds = expirableItems[slug];
    if (expiresInSeconds === undefined) {
      return false;
    }

    // We shouldn't use the getReferenceDate selector here because it returns
    // date only whilst we need the current time as well to properly determine
    // whether the expiration time passed or not.
    return expiresInSeconds > Math.floor(Date.now() / 1000); // eslint-disable-line sitekit/no-direct-date
  })
};
const {
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
} = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.combineStores)({
  initialState: baseInitialState,
  actions: baseActions,
  resolvers: baseResolvers,
  selectors: baseSelectors
}, fetchGetExpirableItemsStore, fetchSetExpirableItemTimersStore);
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/feature-tours.js":
/*!**********************************************************!*\
  !*** ./js/googlesitekit/datastore/user/feature-tours.js ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FEATURE_TOUR_COOLDOWN_SECONDS: () => (/* binding */ FEATURE_TOUR_COOLDOWN_SECONDS),
/* harmony export */   FEATURE_TOUR_LAST_DISMISSED_AT: () => (/* binding */ FEATURE_TOUR_LAST_DISMISSED_AT),
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var compare_versions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! compare-versions */ "../node_modules/compare-versions/index.js");
/* harmony import */ var compare_versions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(compare_versions__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/datastore/site/constants */ "./js/googlesitekit/datastore/site/constants.js");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_feature_tours__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/js/feature-tours */ "./js/feature-tours/index.js");
/* harmony import */ var _js_googlesitekit_api_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/js/googlesitekit/api/cache */ "./js/googlesitekit/api/cache.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * `core/user` data store: feature tours
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */




/**
 * Internal dependencies
 */








const {
  getRegistry
} = googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.commonActions;

// Feature tour cooldown period is 2 hours
const FEATURE_TOUR_COOLDOWN_SECONDS = 60 * 60 * 2;
const FEATURE_TOUR_LAST_DISMISSED_AT = 'feature_tour_last_dismissed_at';

// Actions.
const DISMISS_TOUR = 'DISMISS_TOUR';
const RECEIVE_CURRENT_TOUR = 'RECEIVE_CURRENT_TOUR';
const RECEIVE_READY_TOURS = 'RECEIVE_READY_TOURS';
const RECEIVE_TOURS = 'RECEIVE_TOURS';
const CHECK_TOUR_REQUIREMENTS = 'CHECK_TOUR_REQUIREMENTS';
const CHECK_ON_DEMAND_TOUR_REQUIREMENTS = 'CHECK_ON_DEMAND_TOUR_REQUIREMENTS';
const RECEIVE_LAST_DISMISSED_AT = 'RECEIVE_LAST_DISMISSED_AT';

// Controls.
const fetchGetDismissedToursStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getDismissedTours',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_3__.get)('core', 'user', 'dismissed-tours', {}, {
    useCache: false
  }),
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createReducer)((state, dismissedTourSlugs) => {
    state.dismissedTourSlugs = dismissedTourSlugs;
  })
});
const fetchDismissTourStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'dismissTour',
  controlCallback: ({
    slug
  }) => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_3__.set)('core', 'user', 'dismiss-tour', {
    slug
  }),
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createReducer)((state, dismissedTourSlugs) => {
    state.dismissedTourSlugs = dismissedTourSlugs;
  }),
  argsToParams: slug => ({
    slug
  }),
  validateParams: ({
    slug
  } = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(slug, 'slug is required.');
  }
});
const baseInitialState = {
  lastDismissedAt: undefined,
  dismissedTourSlugs: undefined,
  tours: _js_feature_tours__WEBPACK_IMPORTED_MODULE_8__["default"],
  currentTour: undefined,
  shownTour: undefined
};
const baseActions = {
  /**
   * Dismisses the given tour by slug.
   *
   * @since 1.27.0
   *
   * @param {string} slug Tour slug to dismiss.
   * @return {Object} Generator instance.
   */
  dismissTour: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_10__.createValidatedAction)(slug => {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(slug, 'A tour slug is required to dismiss a tour.');
  }, function* (slug) {
    const {
      select
    } = yield getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).isFetchingDismissTour(slug)) {
      const response = select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getDismissedFeatureTourSlugs();
      return {
        response,
        error: undefined
      };
    }

    // Dismiss the given tour immediately.
    yield {
      type: DISMISS_TOUR,
      payload: {
        slug
      }
    };

    // Save the timestamp to allow the cooldown.
    // The timestamp used here should reflect the actual time the
    // user interacted with this feature tour, not the reference date.
    yield actions.setLastDismissedAt(Date.now()); // eslint-disable-line sitekit/no-direct-date

    // Dispatch a request to persist and receive updated dismissed tours.
    return yield fetchDismissTourStore.actions.fetchDismissTour(slug);
  }),
  receiveCurrentTour(tour) {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()((0,lodash__WEBPACK_IMPORTED_MODULE_2__.isPlainObject)(tour) || (0,lodash__WEBPACK_IMPORTED_MODULE_2__.isNull)(tour), 'tour must be a plain object or null.');
    return {
      payload: {
        tour
      },
      type: RECEIVE_CURRENT_TOUR
    };
  },
  receiveFeatureToursForView(viewTours, {
    viewContext
  } = {}) {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(Array.isArray(viewTours), 'viewTours must be an array.');
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(viewContext, 'viewContext is required.');
    return {
      payload: {
        viewTours,
        viewContext
      },
      type: RECEIVE_READY_TOURS
    };
  },
  receiveAllFeatureTours(tours) {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(Array.isArray(tours), 'tours must be an array.');
    return {
      payload: {
        tours
      },
      type: RECEIVE_TOURS
    };
  },
  receiveLastDismissedAt(timestamp) {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(timestamp !== undefined, 'A timestamp is required.');
    return {
      type: RECEIVE_LAST_DISMISSED_AT,
      payload: {
        timestamp
      }
    };
  },
  setLastDismissedAt: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_10__.createValidatedAction)(timestamp => {
    invariant__WEBPACK_IMPORTED_MODULE_1___default()(timestamp, 'A timestamp is required.');
  }, function* (timestamp) {
    const registry = yield getRegistry();
    registry.dispatch(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_6__.CORE_SITE).setCacheItem(FEATURE_TOUR_LAST_DISMISSED_AT, timestamp, {
      ttl: FEATURE_TOUR_COOLDOWN_SECONDS
    });
    yield {
      type: RECEIVE_LAST_DISMISSED_AT,
      payload: {
        timestamp
      }
    };
  }),
  *triggerTour(tour) {
    const {
      select
    } = yield getRegistry();
    if (!select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getCurrentTour()) {
      yield baseActions.receiveCurrentTour(tour);
    }
  },
  *triggerOnDemandTour(tour) {
    const tourQualifies = yield {
      payload: {
        tour
      },
      type: CHECK_ON_DEMAND_TOUR_REQUIREMENTS
    };
    if (tourQualifies) {
      yield baseActions.triggerTour(tour);
    }
  },
  *triggerTourForView(viewContext) {
    const {
      select,
      resolveSelect
    } = yield getRegistry();
    yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.commonActions.await(resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getLastDismissedAt());
    if (select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).areFeatureToursOnCooldown()) {
      return {};
    }
    const tours = select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getAllFeatureTours();
    for (const tour of tours) {
      const tourQualifies = yield {
        payload: {
          tour,
          viewContext
        },
        type: CHECK_TOUR_REQUIREMENTS
      };
      if (tourQualifies) {
        yield baseActions.triggerTour(tour);
        return tour;
      }
    }

    // Trigger with null here to avoid overriding an on-demand tour.
    yield baseActions.triggerTour(null);
    return null;
  }
};
const baseControls = {
  [CHECK_TOUR_REQUIREMENTS]: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createRegistryControl)(registry => async ({
    payload
  }) => {
    const {
      tour,
      viewContext
    } = payload;

    // Check the view context.
    if (!tour.contexts.includes(viewContext)) {
      return false;
    }

    // Only tours with a version after a user's initial Site Kit version should qualify.
    const initialVersion = await registry.resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getInitialSiteKitVersion();
    if (!initialVersion) {
      return false;
    } else if (compare_versions__WEBPACK_IMPORTED_MODULE_0___default().compare(initialVersion, tour.version, '>=')) {
      return false;
    }

    // Check if the tour has already been dismissed.
    // Here we need to first await the underlying selector with the asynchronous resolver.
    await registry.resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getDismissedFeatureTourSlugs();
    if (registry.select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).isTourDismissed(tour.slug)) {
      return false;
    }

    // If the tour has additional requirements, check those as well.
    if (tour.checkRequirements) {
      return !!(await tour.checkRequirements(registry));
    }
    return true;
  }),
  [CHECK_ON_DEMAND_TOUR_REQUIREMENTS]: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createRegistryControl)(registry => async ({
    payload
  }) => {
    const {
      tour
    } = payload;
    // Check if the tour has already been dismissed.
    // Here we need to first await the underlying selector with the asynchronous resolver.
    await registry.resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getDismissedFeatureTourSlugs();
    if (registry.select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).isTourDismissed(tour.slug)) {
      return false;
    }

    // If the tour has additional requirements, check those as well.
    if (tour.checkRequirements) {
      return !!(await tour.checkRequirements(registry));
    }
    return true;
  })
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case DISMISS_TOUR:
      const {
        slug
      } = payload;
      const {
        dismissedTourSlugs = []
      } = state;
      if (dismissedTourSlugs.includes(slug)) {
        break;
      }
      state.currentTour = state.currentTour?.slug === slug ? null : state.currentTour;
      state.dismissedTourSlugs = dismissedTourSlugs.concat(slug);
      break;
    case RECEIVE_CURRENT_TOUR:
      state.currentTour = payload.tour;
      state.shownTour = payload.tour;
      break;
    case RECEIVE_READY_TOURS:
      const {
        viewContext,
        viewTours
      } = payload;
      state.viewTours = {
        ...state.viewTours,
        [viewContext]: viewTours
      };
      break;
    case RECEIVE_TOURS:
      state.tours = payload.tours;
      break;
    case RECEIVE_LAST_DISMISSED_AT:
      state.lastDismissedAt = payload.timestamp;
      break;
    default:
      break;
  }
});
const baseResolvers = {
  *getDismissedFeatureTourSlugs() {
    const {
      select
    } = yield getRegistry();
    const tours = select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getDismissedFeatureTourSlugs();
    if (tours === undefined) {
      yield fetchGetDismissedToursStore.actions.fetchGetDismissedTours();
    }
  },
  *getLastDismissedAt() {
    const {
      value: lastDismissedAt
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.commonActions.await((0,_js_googlesitekit_api_cache__WEBPACK_IMPORTED_MODULE_9__.getItem)(FEATURE_TOUR_LAST_DISMISSED_AT));
    yield actions.receiveLastDismissedAt(lastDismissedAt || null);
  }
};
const baseSelectors = {
  /**
   * Gets the currently active tour object.
   *
   * @since 1.79.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|null)} Active tour object.
   */
  getCurrentTour(state) {
    return state.currentTour;
  },
  /**
   * Gets the feature tour that has been already shown in the current page view.
   *
   * @since 1.99.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Shown tour object.
   */
  getShownTour(state) {
    return state.shownTour;
  },
  /**
   * Gets the list of dismissed tour slugs.
   *
   * @since 1.27.0
   * @since 1.29.0 Renamed from getDismissedTours.
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {(string[]|undefined)} Array of dismissed tour slugs,
   *                                `undefined` if not resolved yet.
   */
  getDismissedFeatureTourSlugs(state) {
    return state.dismissedTourSlugs;
  },
  /**
   * Gets a list of all tour objects.
   *
   * @since 1.29.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {Object[]} Array of tour objects.
   */
  getAllFeatureTours(state) {
    return state.tours;
  },
  /**
   * Checks whether or not the given tour is dismissed.
   *
   * @since 1.27.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Tour slug to check.
   * @return {(boolean|undefined)} `undefined` if dismissed tours are not loaded yet,
   *                               `true` if dismissed,
   *                               `false` if not dismissed.
   */
  isTourDismissed: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createRegistrySelector)(select => (state, slug) => {
    const dismissedTourSlugs = select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getDismissedFeatureTourSlugs();
    if (undefined === dismissedTourSlugs) {
      return undefined;
    }
    return dismissedTourSlugs.includes(slug);
  }),
  /**
   * Gets the timestamp for the last dismissed feature tour.
   *
   * @since 1.29.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {(number|null|undefined)} Timestamp of the last dismissal
   *                                   `null` if no timestamp exists
   *                                    or `undefined` if value is unresolved.
   */
  getLastDismissedAt(state) {
    return state.lastDismissedAt;
  },
  /**
   * Determines whether feature tours are on cooldown (i.e. the last
   * dismissal was within the cooldown time span).
   *
   * @since 1.29.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {undefined|boolean} Whether feature tours are on cooldown or undefined.
   */
  areFeatureToursOnCooldown: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.createRegistrySelector)(select => () => {
    const lastDismissedAt = select(_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_USER).getLastDismissedAt();
    if (undefined === lastDismissedAt) {
      return undefined;
    }
    // If null, there is no value in the cache, or it has expired.
    if (null === lastDismissedAt) {
      return false;
    }
    const coolDownPeriodMilliseconds = FEATURE_TOUR_COOLDOWN_SECONDS * 1000;
    const coolDownExpiresAt = lastDismissedAt + coolDownPeriodMilliseconds;

    // When using feature tour cooldowns, we should compare the actual
    // time with the cooldown time. Comparing the reference date with
    // the cooldown time expiration would not be accurate (and somewhat
    // confusing during testing).
    return Date.now() < coolDownExpiresAt; // eslint-disable-line sitekit/no-direct-date
  })
};
const {
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
} = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_4__.combineStores)({
  initialState: baseInitialState,
  actions: baseActions,
  controls: baseControls,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
}, fetchDismissTourStore, fetchGetDismissedToursStore);
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/index.js":
/*!**************************************************!*\
  !*** ./js/googlesitekit/datastore/user/index.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   registerStore: () => (/* binding */ registerStore),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/js/googlesitekit/data/create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/* harmony import */ var _adblocker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./adblocker */ "./js/googlesitekit/datastore/user/adblocker.js");
/* harmony import */ var _audience_settings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./audience-settings */ "./js/googlesitekit/datastore/user/audience-settings.js");
/* harmony import */ var _authentication__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./authentication */ "./js/googlesitekit/datastore/user/authentication.js");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _date_range__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./date-range */ "./js/googlesitekit/datastore/user/date-range.js");
/* harmony import */ var _disconnect__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./disconnect */ "./js/googlesitekit/datastore/user/disconnect.js");
/* harmony import */ var _dismissed_items__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./dismissed-items */ "./js/googlesitekit/datastore/user/dismissed-items.js");
/* harmony import */ var _expirable_items__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./expirable-items */ "./js/googlesitekit/datastore/user/expirable-items.js");
/* harmony import */ var _feature_tours__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./feature-tours */ "./js/googlesitekit/datastore/user/feature-tours.js");
/* harmony import */ var _key_metrics__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./key-metrics */ "./js/googlesitekit/datastore/user/key-metrics.js");
/* harmony import */ var _notifications__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./notifications */ "./js/googlesitekit/datastore/user/notifications.js");
/* harmony import */ var _nonces__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./nonces */ "./js/googlesitekit/datastore/user/nonces.js");
/* harmony import */ var _permissions__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./permissions */ "./js/googlesitekit/datastore/user/permissions.js");
/* harmony import */ var _prompts__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./prompts */ "./js/googlesitekit/datastore/user/prompts.js");
/* harmony import */ var _surveys__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./surveys */ "./js/googlesitekit/datastore/user/surveys.js");
/* harmony import */ var _tracking__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./tracking */ "./js/googlesitekit/datastore/user/tracking.js");
/* harmony import */ var _user_info__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./user-info */ "./js/googlesitekit/datastore/user/user-info.js");
/* harmony import */ var _user_input_settings__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./user-input-settings */ "./js/googlesitekit/datastore/user/user-input-settings.js");
/* harmony import */ var _conversion_reporting_settings__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./conversion-reporting-settings */ "./js/googlesitekit/datastore/user/conversion-reporting-settings.js");
/* harmony import */ var _email_reporting_settings__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./email-reporting-settings */ "./js/googlesitekit/datastore/user/email-reporting-settings.js");
/* harmony import */ var _initial_setup_settings__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./initial-setup-settings */ "./js/googlesitekit/datastore/user/initial-setup-settings.js");
/**
 * `core/user` data store
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */























const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__.combineStores)(googlesitekit_data__WEBPACK_IMPORTED_MODULE_0__.commonStore, (0,_js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_1__.createErrorStore)(_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_USER), _adblocker__WEBPACK_IMPORTED_MODULE_2__["default"], _audience_settings__WEBPACK_IMPORTED_MODULE_3__["default"], _authentication__WEBPACK_IMPORTED_MODULE_4__["default"], _date_range__WEBPACK_IMPORTED_MODULE_6__["default"], _disconnect__WEBPACK_IMPORTED_MODULE_7__["default"], _dismissed_items__WEBPACK_IMPORTED_MODULE_8__["default"], _expirable_items__WEBPACK_IMPORTED_MODULE_9__["default"], _feature_tours__WEBPACK_IMPORTED_MODULE_10__["default"], _key_metrics__WEBPACK_IMPORTED_MODULE_11__["default"], _notifications__WEBPACK_IMPORTED_MODULE_12__["default"], _permissions__WEBPACK_IMPORTED_MODULE_14__["default"], _prompts__WEBPACK_IMPORTED_MODULE_15__["default"], _nonces__WEBPACK_IMPORTED_MODULE_13__["default"], _surveys__WEBPACK_IMPORTED_MODULE_16__["default"], _tracking__WEBPACK_IMPORTED_MODULE_17__["default"], _user_info__WEBPACK_IMPORTED_MODULE_18__["default"], _user_input_settings__WEBPACK_IMPORTED_MODULE_19__["default"], _conversion_reporting_settings__WEBPACK_IMPORTED_MODULE_20__["default"], _email_reporting_settings__WEBPACK_IMPORTED_MODULE_21__["default"], _initial_setup_settings__WEBPACK_IMPORTED_MODULE_22__["default"]);
const {
  initialState,
  actions,
  controls,
  reducer,
  resolvers,
  selectors
} = store;
function registerStore(registry) {
  registry.registerStore(_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_USER, store);

  // If a reference date was set by the server, set it in the store.
  if (__webpack_require__.g._googlesitekitBaseData?.referenceDate) {
    registry.dispatch(_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_USER).setReferenceDate(__webpack_require__.g._googlesitekitBaseData.referenceDate);
  }
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/initial-setup-settings.js":
/*!*******************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/initial-setup-settings.js ***!
  \*******************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * `core/user` data store: initial setup settings.
 * Site Kit by Google, Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */






// Actions
const SET_IS_ANALYTICS_SETUP_COMPLETE = 'SET_IS_ANALYTICS_SETUP_COMPLETE';
const baseInitialState = {
  initialSetupSettings: undefined
};
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, initialSetupSettings) => {
  state.initialSetupSettings = initialSetupSettings;
});
const fetchGetInitialSetupSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getInitialSetupSettings',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'initial-setup-settings', undefined, {
    useCache: false
  }),
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveInitialSetupSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'saveInitialSetupSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'initial-setup-settings', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: settings => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Initial setup settings should be an object.');
    if (settings.isAnalyticsSetupComplete !== undefined) {
      invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof settings.isAnalyticsSetupComplete === 'boolean', 'isAnalyticsSetupComplete should be a boolean.');
    }
  }
});
const baseActions = {
  /**
   * Saves the initial setup settings.
   *
   * @since 1.164.0
   *
   * @param {Object} settings Optional. By default, this saves whatever there is in the store. Use this object to save additional settings.
   * @return {Object} Object with `response` and `error`.
   */
  saveInitialSetupSettings: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((settings = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Initial setup settings should be an object to save.');
  }, function* (settings = {}) {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const initialSetupSettings = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(registry.resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getInitialSetupSettings());
    const finalSettings = {
      ...initialSetupSettings,
      ...settings
    };
    return yield fetchSaveInitialSetupSettingsStore.actions.fetchSaveInitialSetupSettings(finalSettings);
  }),
  /* eslint-disable sitekit/jsdoc-no-unnamed-boolean-params */
  /**
   * Sets whether Analytics setup is complete.
   *
   * @since 1.164.0
   *
   * @param {boolean} isAnalyticsSetupComplete Whether or not the Analytics setup is complete.
   * @return {Object} Redux-style action.
   */
  setIsAnalyticsSetupComplete(isAnalyticsSetupComplete) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(typeof isAnalyticsSetupComplete === 'boolean', 'Analytics setup completeness should be a boolean.');
    return {
      type: SET_IS_ANALYTICS_SETUP_COMPLETE,
      payload: {
        isAnalyticsSetupComplete
      }
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case SET_IS_ANALYTICS_SETUP_COMPLETE:
      {
        const {
          isAnalyticsSetupComplete
        } = payload;
        state.initialSetupSettings = {
          ...state.initialSetupSettings,
          isAnalyticsSetupComplete
        };
        break;
      }
    default:
      {
        break;
      }
  }
});
const baseResolvers = {
  *getInitialSetupSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const initialSetupSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getInitialSetupSettings();
    if (initialSetupSettings === undefined) {
      yield fetchGetInitialSetupSettingsStore.actions.fetchGetInitialSetupSettings();
    }
  }
};
const baseSelectors = {
  /**
   * Returns the initial setup settings.
   *
   * @since 1.164.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Initial setup settings.
   */
  getInitialSetupSettings(state) {
    return state.initialSetupSettings;
  },
  /**
   * Returns whether Analytics setup is complete from the initial setup settings.
   *
   * @since 1.164.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|null|undefined)} Whether the Analytics setup is complete or not; `undefined` if not loaded or `null` if not set yet.
   */
  isAnalyticsSetupComplete: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const initialSetupSettings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getInitialSetupSettings();
    return initialSetupSettings?.isAnalyticsSetupComplete;
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetInitialSetupSettingsStore, fetchSaveInitialSetupSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/key-metrics.js":
/*!********************************************************!*\
  !*** ./js/googlesitekit/datastore/user/key-metrics.js ***!
  \********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/datastore/site/constants */ "./js/googlesitekit/datastore/site/constants.js");
/* harmony import */ var _js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/modules/datastore/constants */ "./js/googlesitekit/modules/datastore/constants.js");
/* harmony import */ var _js_googlesitekit_widgets_datastore_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/js/googlesitekit/widgets/datastore/constants */ "./js/googlesitekit/widgets/datastore/constants.js");
/* harmony import */ var _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/js/modules/analytics-4/datastore/constants */ "./js/modules/analytics-4/datastore/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/js/googlesitekit/data/create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/* harmony import */ var _js_components_KeyMetrics_key_metrics_widgets__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/js/components/KeyMetrics/key-metrics-widgets */ "./js/components/KeyMetrics/key-metrics-widgets.js");
/**
 * Site Kit by Google, Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */










const {
  receiveError,
  clearError
} = _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_10__.actions;
const SET_KEY_METRICS_SETTING = 'SET_KEY_METRICS_SETTING';
const baseInitialState = {
  keyMetricsSettings: undefined
};
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, keyMetricsSettings) => {
  state.keyMetricsSettings = keyMetricsSettings;
});
const fetchGetKeyMetricsSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_9__.createFetchStore)({
  baseName: 'getKeyMetricsSettings',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'key-metrics', undefined, {
    // Never cache key metrics requests, we want them to be
    // up-to-date with what's in settings, and they don't
    // make requests to Google APIs so it's not a slow request.
    useCache: false
  }),
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveKeyMetricsSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_9__.createFetchStore)({
  baseName: 'saveKeyMetricsSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'key-metrics', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: settings => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'Settings should be an object.');
  }
});
const baseActions = {
  /**
   * Sets key metrics setting.
   *
   * @since 1.103.0
   *
   * @param {string}         settingID Setting key.
   * @param {Array.<string>} value     Setting value.
   * @return {Object} Redux-style action.
   */
  setKeyMetricsSetting(settingID, value) {
    return {
      type: SET_KEY_METRICS_SETTING,
      payload: {
        settingID,
        value
      }
    };
  },
  /**
   * Saves key metrics settings.
   *
   * @since 1.103.0
   * @since 1.107.0 Accepts an optional `settings` parameter that allows saving additional settings.
   *
   * @param {Object} settings Optional. By default, this saves whatever there is in the store. Use this object to save additional settings.
   * @return {Object} Object with `response` and `error`.
   */
  *saveKeyMetricsSettings(settings = {}) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'key metric settings should be an object to save.');
    yield clearError('saveKeyMetricsSettings', []);
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const keyMetricsSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getKeyMetricsSettings();
    const {
      response,
      error
    } = yield fetchSaveKeyMetricsSettingsStore.actions.fetchSaveKeyMetricsSettings({
      ...keyMetricsSettings,
      ...settings
    });
    if (error) {
      // Store error manually since saveKeyMetrics signature differs from fetchSaveKeyMetricsStore.
      yield receiveError(error, 'saveKeyMetricsSettings', []);
    } else if ((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(settings) || settings.widgetSlugs) {
      // Update the `keyMetricsSetupCompletedBy` value to mark setup completed.
      // This will be handled automatically on the back end.
      registry.dispatch(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_SITE).setKeyMetricsSetupCompletedBy(registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getID());
    }
    return {
      response,
      error
    };
  }
};
const baseControls = {};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, action) => {
  const {
    type,
    payload
  } = action;
  switch (type) {
    case SET_KEY_METRICS_SETTING:
      {
        if (!state.keyMetricsSettings) {
          state.keyMetricsSettings = {};
        }
        state.keyMetricsSettings[payload.settingID] = payload.value;
        break;
      }
    default:
      {
        break;
      }
  }
});
const baseResolvers = {
  *getKeyMetricsSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const keyMetricsSettings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getKeyMetricsSettings();
    if (keyMetricsSettings) {
      return;
    }
    yield fetchGetKeyMetricsSettingsStore.actions.fetchGetKeyMetricsSettings();
  }
};
const baseSelectors = {
  /**
   * Gets currently selected key metrics based on either the user picked metrics or the answer based metrics.
   *
   * @since 1.103.0
   *
   * @return {Array<string>|undefined} An array of key metric slugs, or undefined while loading.
   */
  getKeyMetrics: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const {
      getAnswerBasedMetrics,
      getUserPickedMetrics
    } = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER);
    const userPickedMetrics = getUserPickedMetrics();
    if (userPickedMetrics === undefined) {
      return undefined;
    }
    if (userPickedMetrics.length) {
      return userPickedMetrics;
    }
    const answerBasedMetrics = getAnswerBasedMetrics();
    if (answerBasedMetrics === undefined) {
      return undefined;
    }
    if (answerBasedMetrics.length) {
      return answerBasedMetrics;
    }
    const isKeyMetricsSetupCompleted = select(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_SITE).isKeyMetricsSetupCompleted();
    if (isKeyMetricsSetupCompleted) {
      return [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_NEW_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS];
    }
    return [];
  }),
  /**
   * Gets the Key Metric widget slugs.
   *
   * @since 1.141.0
   *
   * @return {Array<string>|undefined} An array of Key Metric widget slugs.
   */
  getRegularKeyMetricsWidgetIDs: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const postTypes = select(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_SITE).getPostTypes() || [];
    const hasProductPostType = postTypes.some(({
      slug
    }) => slug === 'product');
    return {
      publish_blog: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_RETURNING_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_NEW_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE],
      publish_news: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_PAGES_PER_VISIT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_VISIT_LENGTH, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_VISITS_PER_VISITOR, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_MOST_ENGAGING_PAGES],
      monetize_content: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_NEW_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE],
      sell_products_or_service: [hasProductPostType ? _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_PRODUCTS : _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE],
      sell_products: [hasProductPostType ? _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_PRODUCTS : _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE],
      provide_services: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT],
      share_portfolio: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_NEW_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS]
    };
  }),
  /**
   * Gets the Conversion Key Reporting Metric widget slugs.
   *
   * @since 1.141.0
   *
   * @return {Array<string>|undefined} An array of Key Metric widget slugs.
   */
  getConversionTailoredKeyMetricsWidgetIDs: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, includeConversionTailoredMetrics) => {
    var _select$getPostTypes;
    const postTypes = (_select$getPostTypes = select(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_5__.CORE_SITE).getPostTypes()) !== null && _select$getPostTypes !== void 0 ? _select$getPostTypes : [];
    const hasProductPostType = postTypes.some(({
      slug
    }) => slug === 'product');
    const userInputSettings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings();
    function showConversionTailoredMetrics(events) {
      return events.some(event => userInputSettings?.includeConversionEvents?.values?.includes(event) || Array.isArray(includeConversionTailoredMetrics) && includeConversionTailoredMetrics?.includes(event));
    }
    return {
      publish_blog: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CATEGORIES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS] : [])],
      publish_news: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_AUTHORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CITIES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_RECENT_TRENDING_PAGES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS] : [])],
      monetize_content: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_MOST_ENGAGING_PAGES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_NEW_VISITORS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_VISIT_LENGTH, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_VISITS_PER_VISITOR, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS],
      sell_products_or_service: [hasProductPostType ? _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_PRODUCTS : _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.PURCHASE]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES] : []), ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.ADD_TO_CART]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART] : []), _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS],
      sell_products: [hasProductPostType ? _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_PRODUCTS : _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.PURCHASE]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CITIES_DRIVING_PURCHASES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_DEVICE_DRIVING_PURCHASES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_PURCHASES] : []), ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.ADD_TO_CART]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_ADD_TO_CART] : []), _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ADSENSE_TOP_EARNING_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS],
      provide_services: [...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS] : []), _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_ENGAGED_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES],
      share_portfolio: [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CONVERTING_TRAFFIC_SOURCE, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_RETURNING_VISITOR_PAGES, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_AUTHORS, ...(showConversionTailoredMetrics([_js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.CONTACT, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.GENERATE_LEAD, _js_modules_analytics_4_datastore_constants__WEBPACK_IMPORTED_MODULE_8__.ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM]) ? [_constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_CITIES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_PAGES_DRIVING_LEADS, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_TOP_TRAFFIC_SOURCE_DRIVING_LEADS] : []), _constants__WEBPACK_IMPORTED_MODULE_4__.KM_ANALYTICS_POPULAR_CONTENT, _constants__WEBPACK_IMPORTED_MODULE_4__.KM_SEARCH_CONSOLE_POPULAR_KEYWORDS]
    };
  }),
  /**
   * Gets the Key Metric widget slugs based on the user input settings.
   *
   * @since 1.103.0
   *
   * @return {Array<string>|undefined} An array of Key Metric widget slugs, or undefined if the user input settings are not loaded.
   */
  getAnswerBasedMetrics: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, purposeOverride, includeConversionTailoredMetrics) => {
    const userInputSettings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings();
    if (userInputSettings === undefined) {
      return undefined;
    }
    const purpose = purposeOverride !== null && purposeOverride !== void 0 ? purposeOverride : userInputSettings?.purpose?.values?.[0];
    const widgetIDs = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getConversionTailoredKeyMetricsWidgetIDs(includeConversionTailoredMetrics);
    return widgetIDs[purpose] || [];
  }),
  /**
   * Gets the Key Metric widget slugs selected by the user.
   *
   * @since 1.103.0
   *
   * @return {Array<string>|undefined} An array of Key Metric widget slugs, or undefined if the key metrics settings are not loaded.
   */
  getUserPickedMetrics: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const keyMetricsSettings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getKeyMetricsSettings();
    if (keyMetricsSettings === undefined) {
      return undefined;
    }
    if (!Array.isArray(keyMetricsSettings.widgetSlugs)) {
      return [];
    }

    // Even though a user may have picked their own metrics, there is a chance that they no longer
    // are "available" if they require certain custom dimensions, detected events, feature flags, etc. which no
    // longer exist. So we should filter these out by using the displayInWidgetArea() callback.
    const isViewOnly = !select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).isAuthenticated();
    const filteredWidgetSlugs = keyMetricsSettings.widgetSlugs.filter(slug => {
      const widget = _js_components_KeyMetrics_key_metrics_widgets__WEBPACK_IMPORTED_MODULE_11__.KEY_METRICS_WIDGETS[slug];
      if (!widget) {
        return false;
      }
      if (widget.displayInWidgetArea && typeof widget.displayInWidgetArea === 'function') {
        return widget.displayInWidgetArea({
          select,
          isViewOnlyDashboard: isViewOnly,
          slug
        });
      }
      return true;
    });

    // If only one widget tile remains after filtering, return an empty array.
    // This triggers the `getKeyMetrics` selector to use the default set of widgets
    // instead of hiding the entire widget area (which happens if only one tile is active).
    if (filteredWidgetSlugs.length === 1) {
      return [];
    }
    return filteredWidgetSlugs;
  }),
  /**
   * Gets whether an individual key metric identified by its slug is
   * active or not.
   *
   * @since 1.106.0
   *
   * @return {boolean|undefined} True if the key metric widget tile is active, false if it is not, or undefined if the key metrics settings are not loaded.
   */
  isKeyMetricActive: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, widgetSlug) => {
    const keyMetrics = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getKeyMetrics();
    if (keyMetrics === undefined) {
      return undefined;
    }
    return keyMetrics.includes(widgetSlug);
  }),
  /**
   * Gets whether the key metrics widget is hidden.
   *
   * @since 1.103.0
   *
   * @return {boolean|undefined} True if the key metrics widget is hidden, false if it is not, or undefined if the key metrics settings are not loaded.
   */
  isKeyMetricsWidgetHidden: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const keyMetricsSettings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getKeyMetricsSettings();
    if (keyMetricsSettings === undefined) {
      return undefined;
    }
    return keyMetricsSettings.isWidgetHidden;
  }),
  /**
   * Gets key metrics settings.
   *
   * @since 1.103.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Key metrics settings. Returns `undefined` if not loaded.
   */
  getKeyMetricsSettings(state) {
    const keyMetricsSettings = state.keyMetricsSettings;
    if (!keyMetricsSettings) {
      return undefined;
    }
    return keyMetricsSettings;
  },
  /**
   * Determines whether the key metrics settings are being saved or not.
   *
   * @since 1.107.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the key metrics settings are being saved, otherwise FALSE.
   */
  isSavingKeyMetricsSettings(state) {
    // Since isFetchingSaveKeyMetricsSettings holds information based on specific values but we only need
    // generic information here, we need to check whether ANY such request is in progress.
    return Object.values(state.isFetchingSaveKeyMetricsSettings).some(Boolean);
  },
  /**
   * Gets whether an individual key metric identified by its slug is
   * available, i.e. the modules that it depends on are connected and
   * a view-only user has access to it.
   *
   * @since 1.107.0
   *
   * @param {Object} state      Data store's state.
   * @param {string} widgetSlug The key metric widget slug.
   * @return {boolean|undefined} True if the key metric is available, false if it is not, or undefined if the authentication state has not loaded.
   */
  isKeyMetricAvailable: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (_state, widgetSlug) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(widgetSlug, 'Key metric widget slug required.');
    const isAuthenticated = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).isAuthenticated();
    if (isAuthenticated === undefined) {
      return undefined;
    }
    const widget = select(_js_googlesitekit_widgets_datastore_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_WIDGETS).getWidget(widgetSlug);
    if (!widget) {
      return false;
    }
    const {
      getModule
    } = select(_js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_6__.CORE_MODULES);
    const {
      canViewSharedModule
    } = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER);
    return widget.modules.every(slug => {
      const module = getModule(slug);
      if (!module) {
        return false;
      }
      if (!isAuthenticated && module?.shareable && !canViewSharedModule(slug)) {
        return false;
      }
      return true;
    });
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetKeyMetricsSettingsStore, fetchSaveKeyMetricsSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  controls: baseControls,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/nonces.js":
/*!***************************************************!*\
  !*** ./js/googlesitekit/datastore/user/nonces.js ***!
  \***************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/**
 * `core/user` data store: nonces.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */





// Actions
const RECEIVE_NONCES = 'RECEIVE_NONCES';
const fetchGetNoncesStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
  baseName: 'getNonces',
  controlCallback: () => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__.get)('core', 'user', 'nonces', undefined, {
      useCache: false
    });
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, nonces) => {
    state.nonces = nonces;
  })
});
const baseInitialState = {
  nonces: undefined
};
const baseActions = {
  /**
   * Sets nonces.
   *
   * @since 1.93.0
   *
   * @param {Object} nonces Dictionary of keys and their nonces.
   * @return {Object} Redux-style action.
   */
  receiveNonces(nonces) {
    return {
      type: RECEIVE_NONCES,
      payload: {
        nonces
      }
    };
  }
};
const baseControls = {};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case RECEIVE_NONCES:
      state.nonces = payload.nonces;
      break;
    default:
      break;
  }
});
const baseResolvers = {
  *getNonces() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (registry.select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getNonces()) {
      return;
    }
    yield fetchGetNoncesStore.actions.fetchGetNonces();
  }
};
const baseSelectors = {
  /**
   * Gets all nonces from the store.
   *
   * @since 1.93.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Nonces object. Returns undefined if it is not loaded yet.
   */
  getNonces(state) {
    const {
      nonces
    } = state;
    return nonces;
  },
  /**
   * Gets a single nonce from the store.
   *
   * @since 1.93.0
   *
   * @param {Object} state Data store's state.
   * @param {string} nonce Action name of the nonce to get.
   * @return {(string|undefined)} Nonce string. Returns undefined if this nonce is not loaded yet.
   */
  getNonce: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => (state, nonce) => {
    const nonces = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getNonces();
    if (!nonces) {
      return undefined;
    }
    return nonces[nonce];
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.combineStores)(fetchGetNoncesStore, {
  initialState: baseInitialState,
  actions: baseActions,
  controls: baseControls,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/notifications.js":
/*!**********************************************************!*\
  !*** ./js/googlesitekit/datastore/user/notifications.js ***!
  \**********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _js_googlesitekit_data_create_notifications_store__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/js/googlesitekit/data/create-notifications-store */ "./js/googlesitekit/data/create-notifications-store.js");
/**
 * `core/user` data store: notifications.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */

const notifications = (0,_js_googlesitekit_data_create_notifications_store__WEBPACK_IMPORTED_MODULE_0__.createNotificationsStore)('core', 'user', 'notifications', {
  server: false
});
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (notifications);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/permissions.js":
/*!********************************************************!*\
  !*** ./js/googlesitekit/datastore/user/permissions.js ***!
  \********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/googlesitekit/modules/datastore/constants */ "./js/googlesitekit/modules/datastore/constants.js");
/* harmony import */ var _js_googlesitekit_datastore_util_permissions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/datastore/util/permissions */ "./js/googlesitekit/datastore/util/permissions.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/**
 * `core/user` data store: permission scopes.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */







// Actions
const CLEAR_PERMISSION_SCOPE_ERROR = 'CLEAR_PERMISSION_SCOPE_ERROR';
const SET_PERMISSION_SCOPE_ERROR = 'SET_PERMISSION_SCOPE_ERROR';
const RECEIVE_CAPABILITIES = 'RECEIVE_CAPABILITIES';
const fetchGetCapabilitiesStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_6__.createFetchStore)({
  baseName: 'getCapabilities',
  controlCallback: () => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.get)('core', 'user', 'permissions', undefined, {
      useCache: false
    });
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, capabilities) => {
    state.capabilities = capabilities;
  })
});
const baseInitialState = {
  permissionError: null,
  capabilities: undefined
};
const baseActions = {
  /**
   * Clears the permission scope error, if one was previously set.
   *
   * @since 1.9.0
   * @private
   *
   * @return {Object} Redux-style action.
   */
  clearPermissionScopeError() {
    return {
      payload: {},
      type: CLEAR_PERMISSION_SCOPE_ERROR
    };
  },
  /**
   * Sets a permission error encountered by an API request.
   *
   * @since 1.9.0
   * @private
   *
   * @param {Object} permissionError Permissions error object.
   * @return {Object} Redux-style action.
   */
  setPermissionScopeError(permissionError) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(permissionError, 'permissionError is required.');
    return {
      payload: {
        permissionError
      },
      type: SET_PERMISSION_SCOPE_ERROR
    };
  },
  /**
   * Sets user capabilities.
   *
   * @since 1.13.0
   * @private
   *
   * @param {Object} capabilities User capabilities.
   * @return {Object} Redux-style action.
   */
  receiveCapabilities(capabilities) {
    return {
      type: RECEIVE_CAPABILITIES,
      payload: {
        capabilities
      }
    };
  },
  /**
   * Refreshes user capabilities.
   *
   * @since 1.82.0
   *
   * @return {Object} Redux-style action.
   */
  *refreshCapabilities() {
    const {
      dispatch
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
    const {
      response,
      error
    } = yield fetchGetCapabilitiesStore.actions.fetchGetCapabilities();
    if (error) {
      dispatch(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).setPermissionScopeError(error);
    }
    return {
      response,
      error
    };
  }
};
const baseControls = {};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case CLEAR_PERMISSION_SCOPE_ERROR:
      state.permissionError = null;
      break;
    case SET_PERMISSION_SCOPE_ERROR:
      state.permissionError = payload.permissionError;
      break;
    case RECEIVE_CAPABILITIES:
      state.capabilities = payload.capabilities;
      break;
    default:
      break;
  }
});
const baseResolvers = {
  *getCapabilities() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
    if (registry.select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getCapabilities()) {
      return;
    }

    // Temporary hack to preserve previous behavior when resolved from global.
    // This is necessary for now to avoid a delay if the preloaded data
    // has already expired.
    // We'll still fetch it in case something has changed,
    // but receive the preloaded right away.
    const preloadedPermissions = __webpack_require__.g._googlesitekitAPIFetchData?.preloadedData?.['/google-site-kit/v1/core/user/data/permissions']?.body;
    if (preloadedPermissions) {
      yield fetchGetCapabilitiesStore.actions.receiveGetCapabilities({
        ...preloadedPermissions // dereference.
      });
    }
    yield fetchGetCapabilitiesStore.actions.fetchGetCapabilities();
  }
};
const baseSelectors = {
  /**
   * Gets the most recent permission error encountered by this user.
   *
   * @since 1.9.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {(Object|null)} Permission scope errors. Returns `null` if no error exists.
   */
  getPermissionScopeError(state) {
    const {
      permissionError
    } = state;
    return permissionError;
  },
  /**
   * Gets capabilities of the current user.
   *
   * @since 1.13.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Capabilities object. Returns undefined if it is not loaded yet.
   */
  getCapabilities(state) {
    const {
      capabilities
    } = state;
    return capabilities;
  },
  /**
   * Gets viewable module slugs of the current user.
   *
   * @since 1.72.0
   *
   * @return {(Array|undefined)} An array of viewable module slugs. `undefined` if `modules` are not loaded yet.
   */
  getViewableModules: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => () => {
    const modules = select(_js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_MODULES).getModules();
    if (modules === undefined) {
      return undefined;
    }

    // Return an array of module slugs for modules that are
    // shareable and the user has the "read shared module data"
    // capability for.
    return Object.values(modules).reduce((slugs, module) => {
      const hasCapability = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).hasCapability(_constants__WEBPACK_IMPORTED_MODULE_3__.PERMISSION_READ_SHARED_MODULE_DATA, module.slug);
      if (module.shareable && hasCapability) {
        return [...slugs, module.slug];
      }
      return slugs;
    }, []);
  }),
  /**
   * Checks if the current user has the specified capability or not.
   *
   * @since 1.13.0
   *
   * @param {Object} state      Data store's state.
   * @param {string} capability Capability name to check.
   * @param {Array}  args       List of rest of the arguments. Specifically one or many module slugs.
   * @return {(boolean|undefined)} TRUE if the current user has this capability, otherwise FALSE. If capabilities ain't loaded yet, returns undefined.
   */
  hasCapability: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, capability, ...args) => {
    const capabilities = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getCapabilities();
    if (args.length > 0) {
      capability = (0,_js_googlesitekit_datastore_util_permissions__WEBPACK_IMPORTED_MODULE_5__.getMetaCapabilityPropertyName)(capability, ...args);
    }
    if (capabilities) {
      return !!capabilities[capability];
    }
    return undefined;
  }),
  /**
   * Checks if the specified module is shareable and viewable by the current user.
   *
   * @since 1.77.0
   *
   * @param {Object} state      Data store's state.
   * @param {string} moduleSlug Module slug to check.
   * @return {(boolean|undefined)} `true` if the module is shareable and viewable by the current user. `false` if the module does not exist, is not shareable or not viewable by the current user. `undefined` if state is not loaded yet.
   */
  canViewSharedModule: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, moduleSlug) => {
    const module = select(_js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_MODULES).getModule(moduleSlug);
    if (module === undefined) {
      return undefined;
    }
    if (module === null || !module.shareable) {
      return false;
    }
    return select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).hasCapability(_constants__WEBPACK_IMPORTED_MODULE_3__.PERMISSION_READ_SHARED_MODULE_DATA, module.slug);
  }),
  /**
   * Checks if the current user has access to the specified shareable module.
   *
   * @since 1.120.0
   *
   * @param {Object} state      Data store's state.
   * @param {string} moduleSlug Module slug to check.
   * @return {(boolean|undefined)} `true` if the user is authenticated or if the module is shareable and viewable by the current user. `false` if the module is not shareable or not viewable by the current user. `undefined` if the modules are not loaded yet.
   */
  hasAccessToShareableModule: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, moduleSlug) => {
    const isModuleAvailable = select(_js_googlesitekit_modules_datastore_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_MODULES).isModuleAvailable(moduleSlug);
    if (isModuleAvailable === undefined) {
      return undefined;
    }
    if (isModuleAvailable === false) {
      return false;
    }
    if (select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).isAuthenticated()) {
      return true;
    }
    return select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).canViewSharedModule(moduleSlug);
  })
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.combineStores)(fetchGetCapabilitiesStore, {
  initialState: baseInitialState,
  actions: baseActions,
  controls: baseControls,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/prompts.js":
/*!****************************************************!*\
  !*** ./js/googlesitekit/datastore/user/prompts.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/**
 * `core/user` data store: dismissed prompts
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */





const {
  getRegistry
} = googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions;
const reducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, dismissedPrompts) => {
  state.dismissedPrompts = typeof dismissedPrompts === 'object' ? dismissedPrompts : {};
});
const fetchGetDismissedPromptsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'getDismissedPrompts',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.get)('core', 'user', 'dismissed-prompts', {}, {
    useCache: false
  }),
  reducerCallback
});
const fetchDismissPromptStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_4__.createFetchStore)({
  baseName: 'dismissPrompt',
  controlCallback: ({
    slug,
    expiresInSeconds
  }) => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_1__.set)('core', 'user', 'dismiss-prompt', {
    slug,
    expiration: expiresInSeconds
  }),
  reducerCallback,
  argsToParams: (slug, expiresInSeconds = 0) => {
    return {
      slug,
      expiresInSeconds
    };
  },
  validateParams: ({
    slug,
    expiresInSeconds
  } = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'slug is required.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
  }
});
const baseInitialState = {
  dismissedPrompts: undefined,
  isDismissingPrompts: {}
};
const baseActions = {
  /**
   * Dismisses the given prompt by slug.
   *
   * @since 1.121.0
   *
   * @param {string} slug                       Prompt slug to dismiss.
   * @param {Object} options                    Dismiss prompt options.
   * @param {number} [options.expiresInSeconds] Optional. An integer number of seconds for expiry. 0 denotes permanent dismissal.
   * @return {Object} Generator instance.
   */
  dismissPrompt: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_5__.createValidatedAction)((slug, options = {}) => {
    const {
      expiresInSeconds = 0
    } = options;
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(slug, 'A tour slug is required to dismiss a tour.');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(expiresInSeconds), 'expiresInSeconds must be an integer.');
  }, function* (slug, options = {}) {
    const {
      expiresInSeconds = 0
    } = options;
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.commonActions.getRegistry();
    registry.dispatch(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).setIsPromptDismissing(slug, true);
    const {
      response,
      error
    } = yield fetchDismissPromptStore.actions.fetchDismissPrompt(slug, expiresInSeconds);
    registry.dispatch(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).setIsPromptDismissing(slug, false);
    return {
      response,
      error
    };
  }),
  setIsPromptDismissing(slug, isDismissing) {
    return {
      payload: {
        slug,
        isDismissing
      },
      type: 'SET_IS_PROMPT_DISMISSING'
    };
  }
};
const baseResolvers = {
  *getDismissedPrompts() {
    const {
      select
    } = yield getRegistry();
    const dismissedPrompts = select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getDismissedPrompts();
    if (dismissedPrompts === undefined) {
      yield fetchGetDismissedPromptsStore.actions.fetchGetDismissedPrompts();
    }
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case 'SET_IS_PROMPT_DISMISSING':
      const {
        slug,
        isDismissing
      } = payload;
      state.isDismissingPrompts = {
        [slug]: isDismissing
      };
      break;
    default:
      break;
  }
});
const baseSelectors = {
  /**
   * Gets the list of dismissed prompts.
   *
   * @since 1.121.0
   *
   * @param {Object} state Data store's state.
   * @return {(string[]|undefined)} Array of dismissed prompt keys, `undefined` if there are none.
   */
  getDismissedPrompts(state) {
    if (state.dismissedPrompts === undefined) {
      return undefined;
    }

    // We shouldn't use the getReferenceDate selector here because it returns date only
    // while we need the current time as well to properly determine whether the prompt is
    // expired or not.
    const currentTimeInSeconds = Math.floor(Date.now() / 1000); // eslint-disable-line sitekit/no-direct-date
    return Object.entries(state.dismissedPrompts).reduce((acc, [slug, {
      expires
    }]) => {
      if (expires === 0 || expires > currentTimeInSeconds) {
        acc.push(slug);
      }
      return acc;
    }, []);
  },
  /**
   * Gets the count of a dismissed prompt.
   *
   * @since 1.121.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Prompt slug.
   * @return {(number|undefined)} Count of the prompt, `undefined` if there are none.
   */
  getPromptDismissCount: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(() => (state, slug) => {
    if (!state.dismissedPrompts) {
      return undefined;
    }
    return state.dismissedPrompts[slug]?.count || 0;
  }),
  /**
   * Determines whether the prompt is dismissed or not.
   *
   * @since 1.121.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Prompt slug.
   * @return {(boolean|undefined)} TRUE if dismissed, otherwise FALSE, `undefined` if not resolved yet.
   */
  isPromptDismissed: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.createRegistrySelector)(select => (state, slug) => {
    return select(_constants__WEBPACK_IMPORTED_MODULE_3__.CORE_USER).getDismissedPrompts()?.includes(slug);
  }),
  /**
   * Checks whether or not the prompt is being dismissed for the given slug.
   *
   * @since 1.121.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Prompt slug.
   * @return {boolean} True if the prompt is being dismissed, otherwise false.
   */
  isDismissingPrompt(state, slug) {
    return !!state.isDismissingPrompts[slug];
  }
};
const {
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
} = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_2__.combineStores)({
  initialState: baseInitialState,
  actions: baseActions,
  resolvers: baseResolvers,
  selectors: baseSelectors,
  reducer: baseReducer
}, fetchDismissPromptStore, fetchGetDismissedPromptsStore);
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  actions,
  controls,
  initialState,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/surveys.js":
/*!****************************************************!*\
  !*** ./js/googlesitekit/datastore/user/surveys.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/utils */ "./js/googlesitekit/data/utils.js");
/* harmony import */ var _js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/js/googlesitekit/datastore/site/constants */ "./js/googlesitekit/datastore/site/constants.js");
/**
 * `core/user` data store: Surveys.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */






const fetchTriggerSurveyStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'triggerSurvey',
  controlCallback: ({
    triggerID,
    ttl
  }) => {
    const args = ttl ? {
      ttl
    } : {};
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'survey-trigger', {
      triggerID,
      ...args
    });
  },
  argsToParams: (triggerID, ttl) => {
    return {
      triggerID,
      ttl
    };
  },
  validateParams: ({
    triggerID,
    ttl = 0
  } = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('string' === typeof triggerID && triggerID.length, 'triggerID is required and must be a string');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('number' === typeof ttl, 'ttl must be a number');
  }
});
const fetchSendSurveyEventStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'sendSurveyEvent',
  controlCallback: ({
    event,
    session
  }) => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'survey-event', {
    event,
    session
  }),
  argsToParams: (event, session) => {
    return {
      event,
      session
    };
  }
});
const fetchGetSurveyTimeoutsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getSurveyTimeouts',
  controlCallback() {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'survey-timeouts', {}, {
      useCache: false
    });
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, surveyTimeouts) => {
    state.surveyTimeouts = Array.isArray(surveyTimeouts) ? surveyTimeouts : [];
  })
});
const fetchGetSurveyStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getSurvey',
  controlCallback() {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'survey', {});
  },
  reducerCallback: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, {
    survey
  }) => {
    const {
      survey_payload: currentSurvey = null,
      session: currentSurveySession = null
    } = survey ? survey : {};
    state.currentSurvey = currentSurvey;
    state.currentSurveySession = currentSurveySession;
  })
});
const baseInitialState = {
  currentSurvey: undefined,
  currentSurveySession: undefined,
  lockedSurveyTriggers: {}
};
const LOCK_SURVEY_TRIGGER = 'LOCK_SURVEY_TRIGGER';
const UNLOCK_SURVEY_TRIGGER = 'UNLOCK_SURVEY_TRIGGER';
function lockSurveyTrigger(triggerID) {
  return {
    type: LOCK_SURVEY_TRIGGER,
    payload: {
      triggerID
    }
  };
}
function unlockSurveyTrigger(triggerID) {
  return {
    type: UNLOCK_SURVEY_TRIGGER,
    payload: {
      triggerID
    }
  };
}
const baseActions = {
  /**
   * Triggers a survey.
   *
   * @since 1.34.0
   *
   * @param {string} triggerID     Trigger ID for the survey.
   * @param {Object} options       Survey options.
   * @param {number} [options.ttl] Optional. TTL for survey.
   * @return {Object} Object with `response` and `error`.
   */
  triggerSurvey: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((triggerID, options = {}) => {
    const {
      ttl = 0
    } = options;
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('string' === typeof triggerID && triggerID.length, 'triggerID is required and must be a string');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(options), 'options must be an object');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('number' === typeof ttl, 'options.ttl must be a number');
  }, function* (triggerID, options = {}) {
    const {
      ttl = 0
    } = options;
    const {
      select,
      resolveSelect
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const {
      isAuthenticated,
      isSurveyTimedOut,
      isSurveyTriggerLocked,
      getSurveyTimeouts
    } = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER);
    // eslint-disable-next-line @wordpress/no-unused-vars-before-return
    const {
      isUsingProxy
    } = select(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_SITE);

    // The lock prevents multiple concurrent triggers for the same ID.
    if (isSurveyTriggerLocked(triggerID)) {
      return {};
    }
    yield lockSurveyTrigger(triggerID);
    try {
      // Wait for state to be available before selecting.
      yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(Promise.all([resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getAuthentication(), resolveSelect(_js_googlesitekit_datastore_site_constants__WEBPACK_IMPORTED_MODULE_7__.CORE_SITE).getSiteInfo()]));
      if (!isAuthenticated() || !isUsingProxy()) {
        return {};
      }
      yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getSurveyTimeouts());

      // Check if persistent timeout for this trigger is set
      // or if an in-memory timeout is present (see below).
      if (isSurveyTimedOut(triggerID)) {
        return {
          response: {},
          error: false
        };
      }
      const {
        response,
        error
      } = yield fetchTriggerSurveyStore.actions.fetchTriggerSurvey(triggerID, ttl);
      if (error) {
        return {
          response,
          error
        };
      }
      if (ttl > 0) {
        // Survey timeouts should be available here; fallback to empty array in case of error.
        const timeouts = getSurveyTimeouts() || [];
        // Add the trigger to the list of timeouts directly (next time it will come from server side).
        yield fetchGetSurveyTimeoutsStore.actions.receiveGetSurveyTimeouts([...timeouts, triggerID]);
      }
      return {
        response: {},
        error: false
      };
    } finally {
      yield unlockSurveyTrigger(triggerID);
    }
  }),
  /**
   * Sends a survey event.
   *
   * @since 1.34.0
   *
   * @param {string} eventID   Event ID for the survey.
   * @param {Object} eventData Event data.
   * @return {Object} Object with `response` and `error`.
   */
  sendSurveyEvent: (0,_js_googlesitekit_data_utils__WEBPACK_IMPORTED_MODULE_6__.createValidatedAction)((eventID, eventData = {}) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()('string' === typeof eventID && eventID.length, 'eventID is required and must be a string');
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(eventData), 'eventData must be an object');
  }, function* (eventID, eventData = {}) {
    const event = {
      [eventID]: eventData
    };
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const session = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getCurrentSurveySession();
    if (session) {
      const {
        response,
        error
      } = yield fetchSendSurveyEventStore.actions.fetchSendSurveyEvent(event, session);
      return {
        response,
        error
      };
    }
    return {
      response: null,
      error: 'no session found'
    };
  })
};
const baseResolvers = {
  *getCurrentSurvey() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const currentSurvey = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getCurrentSurvey();
    if (currentSurvey === undefined) {
      yield fetchGetSurveyStore.actions.fetchGetSurvey();
    }
  },
  *getSurveyTimeouts() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const surveyTimeouts = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getSurveyTimeouts();
    if (surveyTimeouts === undefined) {
      yield fetchGetSurveyTimeoutsStore.actions.fetchGetSurveyTimeouts();
    }
  }
};
const baseSelectors = {
  /**
   * Gets the current survey.
   *
   * @since 1.34.0
   *
   * @param {Object} state Data store's state.
   * @return {Object} Current survey object.
   */
  getCurrentSurvey(state) {
    return state.currentSurvey;
  },
  /**
   * Gets the current survey session.
   *
   * @since 1.34.0
   *
   * @param {Object} state Data store's state.
   * @return {Object} Current survey session object.
   */
  getCurrentSurveySession(state) {
    return state.currentSurveySession;
  },
  /**
   * Gets the completion triggers for the current survey, if one exists.
   *
   * @since 1.35.0
   *
   * @return {Array|null} Current survey's completion triggers if available; `null` if no questions/survey are found.
   */
  getCurrentSurveyCompletions: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const currentSurvey = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getCurrentSurvey();
    return currentSurvey?.completion || null;
  }),
  /**
   * Gets the questions from the current survey, if one exists.
   *
   * @since 1.35.0
   *
   * @return {Array|null} Current survey's questions if available; `null` if no questions/survey are found.
   */
  getCurrentSurveyQuestions: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    const currentSurvey = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getCurrentSurvey();
    return currentSurvey?.question || null;
  }),
  /**
   * Gets the list of survey timeouts.
   *
   * @since 1.73.0
   *
   * @param {Object} state Data store's state.
   * @return {(string[]|undefined)} Array of surveys slugs, `undefined` if not resolved yet.
   */
  getSurveyTimeouts(state) {
    return state.surveyTimeouts;
  },
  /**
   * Determines whether the survey is timed out or not.
   *
   * @since 1.73.0
   *
   * @param {Object} state Data store's state.
   * @param {string} slug  Item slug.
   * @return {(boolean|undefined)} TRUE if timed out, otherwise FALSE, `undefined` if not resolved yet.
   */
  isSurveyTimedOut: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, slug) => {
    const timeouts = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getSurveyTimeouts();
    return timeouts === undefined ? undefined : timeouts.includes(slug);
  }),
  /**
   * Checks if the given survey trigger is currently locked.
   *
   * @since 1.147.0
   *
   * @param {Object} state     Data store's state.
   * @param {string} triggerID Survey trigger ID.
   * @return {boolean} TRUE if locked, otherwise FALSE.
   */
  isSurveyTriggerLocked(state, triggerID) {
    return !!state.lockedSurveyTriggers[triggerID];
  },
  /**
   * Determines whether surveys are on cooldown or not.
   *
   * @since 1.98.0
   *
   * @return {(boolean|undefined)} TRUE if surveys are on cooldown, otherwise FALSE, `undefined` if not resolved yet.
   */
  areSurveysOnCooldown: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => () => {
    return select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).isSurveyTimedOut(_constants__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_SURVEYS_TIMEOUT_SLUG);
  })
};
const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, action) => {
  switch (action.type) {
    case LOCK_SURVEY_TRIGGER:
      {
        const {
          triggerID
        } = action.payload;
        state.lockedSurveyTriggers[triggerID] = true;
        break;
      }
    case UNLOCK_SURVEY_TRIGGER:
      {
        const {
          triggerID
        } = action.payload;
        state.lockedSurveyTriggers[triggerID] = false;
      }
  }
});
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchTriggerSurveyStore, fetchSendSurveyEventStore, fetchGetSurveyTimeoutsStore, fetchGetSurveyStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/tracking.js":
/*!*****************************************************!*\
  !*** ./js/googlesitekit/datastore/user/tracking.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   baseReducer: () => (/* binding */ baseReducer),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/js/googlesitekit/data/create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/**
 * `core/user` data store: Tracking info.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable sitekit/jsdoc-no-unnamed-boolean-params */

/**
 * Internal dependencies
 */





const {
  receiveError,
  clearError
} = _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_4__.actions;
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, tracking) => {
  state.tracking = tracking;
});
const fetchGetTrackingStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
  baseName: 'getTracking',
  controlCallback: () => {
    return (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__.get)('core', 'user', 'tracking');
  },
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveTrackingStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_3__.createFetchStore)({
  baseName: 'setTracking',
  controlCallback: enabled => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_0__.set)('core', 'user', 'tracking', {
    enabled: !!enabled
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: enabled => enabled
});
const baseInitialState = {
  tracking: undefined,
  isSavingTrackingEnabled: false
};

// Actions
const SET_TRACKING_ENABLED_SAVING_ACTION = 'SET_TRACKING_ENABLED_SAVING_ACTION';
const baseActions = {
  /**
   * Sets user tracking settings.
   *
   * @since 1.28.0
   *
   * @param {boolean} enabled Tracking status.
   * @return {Object} Object with `response` and `error`.
   */
  *setTrackingEnabled(enabled) {
    yield clearError('setTrackingEnabled', [enabled]);
    yield {
      type: SET_TRACKING_ENABLED_SAVING_ACTION,
      payload: {
        isSaving: true
      }
    };
    const {
      response,
      error
    } = yield fetchSaveTrackingStore.actions.fetchSetTracking(enabled);
    if (error) {
      yield receiveError(error, 'setTrackingEnabled', [enabled]);
    }
    yield {
      type: SET_TRACKING_ENABLED_SAVING_ACTION,
      payload: {
        isSaving: false
      }
    };
    return {
      response,
      error
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case SET_TRACKING_ENABLED_SAVING_ACTION:
      state.isSavingTrackingEnabled = payload.isSaving;
      break;
    default:
      break;
  }
});
const baseResolvers = {
  *isTrackingEnabled() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).isTrackingEnabled() === undefined) {
      yield fetchGetTrackingStore.actions.fetchGetTracking();
    }
  }
};
const baseSelectors = {
  /**
   * Determines whether the user tracking settings are being saved or not.
   *
   * @since 1.28.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the user tracking settings are being saved, otherwise FALSE.
   */
  isSavingTrackingEnabled(state) {
    return !!state?.isSavingTrackingEnabled;
  },
  /**
   * Determines whether the user tracking is enabled or not.
   *
   * @since 1.28.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} TRUE if user tracking enabled, otherwise FALSE.
   */
  isTrackingEnabled(state) {
    const {
      tracking
    } = state;
    return tracking?.enabled;
  }
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.combineStores)(fetchGetTrackingStore, fetchSaveTrackingStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/user/user-info.js":
/*!******************************************************!*\
  !*** ./js/googlesitekit/datastore/user/user-info.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _wordpress_url__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @wordpress/url */ "../node_modules/@wordpress/url/build-module/add-query-args.js");
/* harmony import */ var _wordpress_url__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @wordpress/url */ "../node_modules/@wordpress/url/build-module/has-query-arg.js");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_util_escape_uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/js/util/escape-uri */ "./js/util/escape-uri.ts");
/**
 * `core/user` data store: user info
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable sitekit/jsdoc-no-unnamed-boolean-params */

/**
 * External dependencies
 */


/**
 * WordPress dependencies
 */


/**
 * Internal dependencies
 */



const RECEIVE_CONNECT_URL = 'RECEIVE_CONNECT_URL';
const RECEIVE_USER_INFO = 'RECEIVE_USER_INFO';
const RECEIVE_USER_IS_VERIFIED = 'RECEIVE_USER_IS_VERIFIED';
const RECEIVE_IS_USER_INPUT_COMPLETED = 'RECEIVE_IS_USER_INPUT_COMPLETED';
const RECEIVE_USER_INITIAL_SITE_KIT_VERSION = 'RECEIVE_USER_INITIAL_SITE_KIT_VERSION';
const initialState = {
  connectURL: undefined,
  initialVersion: undefined,
  user: undefined,
  verified: undefined,
  isUserInputCompleted: undefined
};
const actions = {
  /**
   * Stores the OAuth connection URL in the datastore.
   *
   * @since 1.9.0
   * @private
   *
   * @param {string} connectURL Full URL to the Site Kit googlesitekit_connect handler.
   * @return {Object} Redux-style action.
   */
  receiveConnectURL(connectURL) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(connectURL, 'connectURL is required.');
    return {
      payload: {
        connectURL
      },
      type: RECEIVE_CONNECT_URL
    };
  },
  /**
   * Stores user info in the datastore.
   *
   * Because this is frequently-accessed data, this is usually sourced
   * from a global variable (`_googlesitekitUserData`), set by PHP
   * in the `before_print` callback for `googlesitekit-datastore-user`.
   *
   * @since 1.9.0
   * @private
   *
   * @param {Object} userInfo User info, usually supplied via a global variable from PHP.
   * @return {Object} Redux-style action.
   */
  receiveUserInfo(userInfo) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(userInfo, 'userInfo is required.');
    return {
      payload: {
        user: userInfo
      },
      type: RECEIVE_USER_INFO
    };
  },
  receiveInitialSiteKitVersion(initialVersion) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(initialVersion, 'initialVersion is required.');
    return {
      payload: {
        initialVersion
      },
      type: RECEIVE_USER_INITIAL_SITE_KIT_VERSION
    };
  },
  /**
   * Stores user verification status in the datastore.
   *
   * Because this is frequently-accessed data, this is usually sourced
   * from a global variable (`_googlesitekitUserData`), set by PHP
   * in the `before_print` callback for `googlesitekit-datastore-user`.
   *
   * @since 1.9.0
   * @private
   *
   * @param {boolean} userIsVerified User verification status, usually supplied via a global variable from PHP.
   * @return {Object} Redux-style action.
   */
  receiveUserIsVerified(userIsVerified) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(userIsVerified !== undefined, 'userIsVerified is required.');
    return {
      payload: {
        verified: userIsVerified
      },
      type: RECEIVE_USER_IS_VERIFIED
    };
  },
  /**
   * Stores the user input state in the datastore.
   *
   * @since 1.94.0
   * @private
   *
   * @param {Object} isUserInputCompleted User input state.
   * @return {Object} Redux-style action.
   */
  receiveIsUserInputCompleted(isUserInputCompleted) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(isUserInputCompleted !== undefined, 'The isUserInputCompleted param is required.');
    return {
      payload: {
        isUserInputCompleted
      },
      type: RECEIVE_IS_USER_INPUT_COMPLETED
    };
  }
};
const controls = {};
const reducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createReducer)((state, {
  type,
  payload
}) => {
  switch (type) {
    case RECEIVE_CONNECT_URL:
      state.connectURL = payload.connectURL;
      break;
    case RECEIVE_USER_INFO:
      state.user = payload.user;
      break;
    case RECEIVE_USER_INITIAL_SITE_KIT_VERSION:
      state.initialVersion = payload.initialVersion;
      break;
    case RECEIVE_USER_IS_VERIFIED:
      state.verified = payload.verified;
      break;
    case RECEIVE_IS_USER_INPUT_COMPLETED:
      state.isUserInputCompleted = payload.isUserInputCompleted;
      break;
    default:
      break;
  }
});
const resolvers = {
  *getConnectURL() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getConnectURL()) {
      return;
    }
    if (!__webpack_require__.g._googlesitekitUserData) {
      __webpack_require__.g.console.error('Could not load core/user info.');
      return;
    }
    const {
      connectURL
    } = __webpack_require__.g._googlesitekitUserData;
    yield actions.receiveConnectURL(connectURL);
  },
  *getUser() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser() !== undefined) {
      return;
    }
    if (!__webpack_require__.g._googlesitekitUserData) {
      __webpack_require__.g.console.error('Could not load core/user info.');
      return;
    }
    const {
      user
    } = __webpack_require__.g._googlesitekitUserData;
    yield actions.receiveUserInfo(user);
  },
  *getInitialSiteKitVersion() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getInitialSiteKitVersion() !== undefined) {
      return;
    }
    if (!__webpack_require__.g._googlesitekitUserData) {
      __webpack_require__.g.console.error('Could not load core/user info.');
      return;
    }
    const {
      initialVersion
    } = __webpack_require__.g._googlesitekitUserData;
    if (initialVersion) {
      yield actions.receiveInitialSiteKitVersion(initialVersion);
    }
  },
  *isVerified() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).isVerified() !== undefined) {
      return;
    }
    if (!__webpack_require__.g._googlesitekitUserData) {
      __webpack_require__.g.console.error('Could not load core/user info.');
      return;
    }
    const {
      verified
    } = __webpack_require__.g._googlesitekitUserData;
    yield actions.receiveUserIsVerified(verified);
  },
  *isUserInputCompleted() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.commonActions.getRegistry();
    if (undefined !== select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).isUserInputCompleted()) {
      return;
    }
    if (!__webpack_require__.g._googlesitekitUserData) {
      __webpack_require__.g.console.error('Could not load core/user info.');
      return;
    }
    const {
      isUserInputCompleted
    } = __webpack_require__.g._googlesitekitUserData;
    yield actions.receiveIsUserInputCompleted(isUserInputCompleted);
  }
};
const selectors = {
  /**
   * Gets the user info for the logged in user.
   *
   * Returns `undefined` if the user info is not available/loaded.
   *
   * Returns an object with the shape when successful:
   * ```
   * {
   *   user: <Object>,
   *   verified: <Boolean>,
   * }
   * ```
   *
   * @since 1.9.0
   * @private
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} User info.
   */
  getUser(state) {
    const {
      user
    } = state;
    return user;
  },
  /**
   * Gets a URL for (re)connecting via OAuth, with optional additional scopes.
   *
   * @since 1.9.0
   * @since 1.34.1 Updated resulting URL when additional scopes are provided.
   *
   * @param {Object}   state                   Data store's state.
   * @param {Object}   [args]                  Optional arguments for the resulting URL.
   * @param {string[]} [args.additionalScopes] Additional scopes to request.
   * @param {string}   [args.redirectURL]      URL to redirect to after successful authentication.
   * @param {string}   [args.errorRedirectURL] URL to redirect to if an error is returned during authentication.
   * @return {(string|undefined)} Full URL to connect, or `undefined` if not loaded yet.
   */
  getConnectURL(state, {
    additionalScopes = [],
    redirectURL = undefined,
    errorRedirectURL = undefined
  } = {}) {
    const {
      connectURL
    } = state;
    const queryArgs = {
      redirect: redirectURL,
      errorRedirect: errorRedirectURL
    };
    if (connectURL === undefined) {
      return undefined;
    }

    // If additional scopes are provided, pass them in the dedicated query param.
    if (additionalScopes?.length) {
      // Some hosts with aggressive security filters block URLs with query parameters
      // that begin with a URL. This will block these requests because most scopes
      // are valid URLs. As a workaround, we rewrite the scheme temporarily
      // and then restore it on the server before requesting scopes.
      const rewrittenScopes = additionalScopes.map(scope => scope.replace(/^http(s)?:/, 'gttp$1:'));
      return (0,_wordpress_url__WEBPACK_IMPORTED_MODULE_4__.addQueryArgs)(connectURL, {
        ...queryArgs,
        additional_scopes: rewrittenScopes
      });
    }
    return (0,_wordpress_url__WEBPACK_IMPORTED_MODULE_4__.addQueryArgs)(connectURL, queryArgs);
  },
  /**
   * Gets the ID for this user.
   *
   * Returns ID of the user or `undefined` if the user info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(number|undefined)} The user ID.
   */
  getID: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const user = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser();
    return user !== undefined ? user.id : user;
  }),
  /**
   * Gets the Name for this user.
   *
   * Returns Name of the user or `undefined` if the user info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The user ID.
   */
  getName: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const user = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser();
    return user !== undefined ? user.name : user;
  }),
  /**
   * Gets the Email for this user.
   *
   * Returns email of the user or `undefined` if the user info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The user ID.
   */
  getEmail: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const user = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser();
    return user !== undefined ? user.email : user;
  }),
  /**
   * Gets the url to the picture for this user.
   *
   * Returns url of the user picture or `undefined` if the user info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The user ID.
   */
  getPicture: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const user = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser();
    return user !== undefined ? user.picture : user;
  }),
  /**
   * Gets the full name name for this user.
   *
   * Returns full name of the user or `undefined` if the user info is not available/loaded.
   *
   * @since 1.86.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|null|undefined)} The user's full name; will be set to `null` if not available in the user's profile data and `undefined` while loading.
   */
  getFullName: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => () => {
    const user = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getUser();
    if (user === undefined) {
      return undefined;
    }
    return user.full_name;
  }),
  /**
   * Gets an account chooser url with the current user's email.
   *
   * @since 1.80.0
   * @since 1.168.0 Adds `utm_source` to wrapper and wrapped URL.
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} The concatenated url if an email is present; otherwise undefined.
   */
  getAccountChooserURL: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_1__.createRegistrySelector)(select => (state, destinationURL) => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(destinationURL, 'destinationURL is required');
    const userEmail = select(_constants__WEBPACK_IMPORTED_MODULE_2__.CORE_USER).getEmail();
    if (userEmail === undefined) {
      return undefined;
    }

    // Add `utm_source` to the `destinationURL` if it doesn't already exist.
    if (!(0,_wordpress_url__WEBPACK_IMPORTED_MODULE_5__.hasQueryArg)(destinationURL, 'utm_source')) {
      destinationURL = (0,_wordpress_url__WEBPACK_IMPORTED_MODULE_4__.addQueryArgs)(destinationURL, {
        utm_source: 'sitekit'
      });
    }

    // The `Email` parameter is case sensitive;
    // the capital E is required for the account chooser URL.
    return (0,_js_util_escape_uri__WEBPACK_IMPORTED_MODULE_3__.escapeURI)`https://accounts.google.com/accountchooser?continue=${destinationURL}&Email=${userEmail}&utm_source=sitekit`;
  }),
  /**
   * Gets the initial version that the user used Site Kit with.
   *
   * @since 1.27.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} `string` Site Kit version number,
   *                              `undefined` if not resolve yet.
   */
  getInitialSiteKitVersion(state) {
    return state.initialVersion;
  },
  /**
   * Gets the verified status for this user.
   *
   * Returns the true if the user is verified, false if not verified, or `undefined` if the user info is not available/loaded.
   *
   * @since 1.9.0
   *
   * @param {Object} state Data store's state.
   * @return {(boolean|undefined)} The user ID.
   */
  isVerified(state) {
    const {
      verified
    } = state;
    return verified;
  },
  /**
   * Gets the user input state.
   *
   * @since 1.94.0
   *
   * @param {Object} state Data store's state.
   * @return {string} The user input state.
   */
  isUserInputCompleted(state) {
    const {
      isUserInputCompleted
    } = state;
    return isUserInputCompleted;
  }
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({
  initialState,
  actions,
  controls,
  reducer,
  resolvers,
  selectors
});

/***/ }),

/***/ "./js/googlesitekit/datastore/user/user-input-settings.js":
/*!****************************************************************!*\
  !*** ./js/googlesitekit/datastore/user/user-input-settings.js ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   actions: () => (/* binding */ actions),
/* harmony export */   baseReducer: () => (/* binding */ baseReducer),
/* harmony export */   controls: () => (/* binding */ controls),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   initialState: () => (/* binding */ initialState),
/* harmony export */   reducer: () => (/* binding */ reducer),
/* harmony export */   resolvers: () => (/* binding */ resolvers),
/* harmony export */   selectors: () => (/* binding */ selectors)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! googlesitekit-api */ "googlesitekit-api");
/* harmony import */ var googlesitekit_api__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! googlesitekit-data */ "googlesitekit-data");
/* harmony import */ var googlesitekit_data__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants */ "./js/googlesitekit/datastore/user/constants.js");
/* harmony import */ var _js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/js/googlesitekit/data/create-fetch-store */ "./js/googlesitekit/data/create-fetch-store.js");
/* harmony import */ var _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/js/googlesitekit/data/create-error-store */ "./js/googlesitekit/data/create-error-store.js");
/**
 * `core/user` settings store: user input settings.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * Internal dependencies
 */





const {
  receiveError,
  clearError
} = _js_googlesitekit_data_create_error_store__WEBPACK_IMPORTED_MODULE_6__.actions;
const fetchStoreReducerCallback = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, inputSettings) => {
  state.inputSettings = inputSettings;
  state.savedInputSettings = inputSettings;
});
const fetchGetUserInputSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'getUserInputSettings',
  controlCallback: () => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.get)('core', 'user', 'user-input-settings', undefined, {
    useCache: false
  }),
  reducerCallback: fetchStoreReducerCallback
});
const fetchSaveUserInputSettingsStore = (0,_js_googlesitekit_data_create_fetch_store__WEBPACK_IMPORTED_MODULE_5__.createFetchStore)({
  baseName: 'saveUserInputSettings',
  controlCallback: settings => (0,googlesitekit_api__WEBPACK_IMPORTED_MODULE_2__.set)('core', 'user', 'user-input-settings', {
    settings
  }),
  reducerCallback: fetchStoreReducerCallback,
  argsToParams: settings => settings,
  validateParams: settings => {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(settings), 'valid settings are required.');
  }
});

// Actions
const SET_USER_INPUT_SETTING = 'SET_USER_INPUT_SETTING';
const SET_USER_INPUT_SETTINGS_SAVING_FLAG = 'SET_USER_INPUT_SETTINGS_SAVING_FLAG';
const RESET_USER_INPUT_SETTINGS = 'RESET_USER_INPUT_SETTINGS';
const baseInitialState = {
  inputSettings: undefined,
  isSavingInputSettings: false,
  savedInputSettings: undefined
};
const baseActions = {
  /**
   * Sets user input setting.
   *
   * @since 1.19.0 Function introduced.
   *
   * @param {string}         settingID Setting key.
   * @param {Array.<string>} values    User input settings.
   * @return {Object} Redux-style action.
   */
  setUserInputSetting(settingID, values) {
    return {
      type: SET_USER_INPUT_SETTING,
      payload: {
        settingID,
        values: values.map(value => value.trim())
      }
    };
  },
  /**
   * Saves user input settings.
   *
   * @since 1.19.0
   *
   * @return {Object} Object with `response` and `error`.
   */
  *saveUserInputSettings() {
    const registry = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    yield clearError('saveUserInputSettings', []);
    function trim(value) {
      return value.trim();
    }
    function notEmpty(value) {
      return value.length > 0;
    }
    const settings = registry.select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings();
    const values = Object.keys(settings).reduce((accum, key) => ({
      ...accum,
      [key]: (settings[key]?.values || []).map(trim).filter(notEmpty)
    }), {});
    yield {
      type: SET_USER_INPUT_SETTINGS_SAVING_FLAG,
      payload: {
        isSaving: true
      }
    };
    const {
      response,
      error
    } = yield fetchSaveUserInputSettingsStore.actions.fetchSaveUserInputSettings(values);
    if (error) {
      // Store error manually since saveUserInputSettings signature differs from fetchSaveUserInputSettings.
      yield receiveError(error, 'saveUserInputSettings', []);
    }
    if (!error) {
      yield baseActions.maybeTriggerUserInputSurvey();
    }
    yield {
      type: SET_USER_INPUT_SETTINGS_SAVING_FLAG,
      payload: {
        isSaving: false
      }
    };
    return {
      response,
      error
    };
  },
  /**
   * Resets modified user input settings to currently saved values.
   *
   * @since 1.93.0
   *
   * @return {Object} Redux-style action.
   */
  *resetUserInputSettings() {
    return {
      type: RESET_USER_INPUT_SETTINGS,
      payload: {}
    };
  },
  /**
   * Triggers user input survey if any of the answers is "Other".
   *
   * @since 1.104.0
   *
   * @return {Object} Object with `response` and `error`.
   */
  *maybeTriggerUserInputSurvey() {
    const {
      resolveSelect,
      dispatch
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    const settings = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(resolveSelect(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings());
    const settingsAnsweredOther = Object.keys(settings).filter(key => settings[key].values.includes('other'));
    if (!settingsAnsweredOther.length > 0) {
      return {};
    }
    const triggerID = `userInput_answered_other__${settingsAnsweredOther.join('_')}`;
    const {
      response,
      error
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.await(dispatch(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).triggerSurvey(triggerID));
    return {
      response,
      error
    };
  }
};
const baseReducer = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createReducer)((state, action) => {
  const {
    type,
    payload
  } = action;
  switch (type) {
    case SET_USER_INPUT_SETTING:
      {
        state.inputSettings = state.inputSettings || {};
        if (!state.inputSettings[payload.settingID]) {
          state.inputSettings[payload.settingID] = {};
        }
        state.inputSettings[payload.settingID].values = payload.values;
        break;
      }
    case SET_USER_INPUT_SETTINGS_SAVING_FLAG:
      {
        state.isSavingInputSettings = payload.isSaving;
        break;
      }
    case RESET_USER_INPUT_SETTINGS:
      {
        state.inputSettings = state.savedInputSettings;
        break;
      }
    default:
      break;
  }
});
const baseResolvers = {
  *getUserInputSettings() {
    const {
      select
    } = yield googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.commonActions.getRegistry();
    if (!select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings()) {
      yield fetchGetUserInputSettingsStore.actions.fetchGetUserInputSettings();
    }
  }
};
const baseSelectors = {
  /**
   * Determines whether the user input settings are being saved or not.
   *
   * @since 1.25.0
   *
   * @param {Object} state Data store's state.
   * @return {boolean} TRUE if the user input settings are being saved, otherwise FALSE.
   */
  isSavingUserInputSettings(state) {
    return !!state?.isSavingInputSettings;
  },
  /**
   * Gets input settings info for this user.
   *
   * @since 1.19.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} User input settings.
   */
  getUserInputSettings(state) {
    const {
      inputSettings
    } = state;
    return inputSettings;
  },
  /**
   * Gets saved input settings info for this user.
   *
   * @since 1.141.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} Saved user input settings.
   */
  getSavedUserInputSettings(state) {
    const {
      savedInputSettings
    } = state;
    return savedInputSettings;
  },
  /**
   * Gets a particular input setting.
   *
   * @since 1.19.0
   *
   * @param {Object} state Data store's state.
   * @return {(Array.<string>|undefined)} User input setting values.
   */
  getUserInputSetting: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, settingID) => {
    const settings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings() || {};
    const values = settings[settingID]?.values;
    return Array.isArray(values) ? values : [];
  }),
  /**
   * Gets a scope of the input setting.
   *
   * @since 1.20.0
   *
   * @param {Object} state Data store's state.
   * @return {(string|undefined)} User input setting scope.
   */
  getUserInputSettingScope: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, settingID) => {
    const settings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings() || {};
    return settings[settingID]?.scope;
  }),
  /**
   * Gets an author of the input setting.
   *
   * @since 1.20.0
   *
   * @param {Object} state Data store's state.
   * @return {(Object|undefined)} User input setting author.
   */
  getUserInputSettingAuthor: (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.createRegistrySelector)(select => (state, settingID) => {
    const settings = select(_constants__WEBPACK_IMPORTED_MODULE_4__.CORE_USER).getUserInputSettings() || {};
    return settings[settingID]?.author;
  }),
  /**
   * Indicates whether the current user input settings have changed from what is saved.
   *
   * @since 1.93.0
   *
   * @param {Object}     state Data store's state.
   * @param {Array|null} keys  Settings keys to check; if not provided, all settings are checked.
   * @return {boolean} True if the settings have changed, false otherwise.
   */
  haveUserInputSettingsChanged(state, keys = null) {
    const {
      inputSettings,
      savedInputSettings
    } = state;
    if (keys) {
      return !(0,lodash__WEBPACK_IMPORTED_MODULE_1__.isEqual)((0,lodash__WEBPACK_IMPORTED_MODULE_1__.pick)(inputSettings, keys), (0,lodash__WEBPACK_IMPORTED_MODULE_1__.pick)(savedInputSettings, keys));
    }
    return !(0,lodash__WEBPACK_IMPORTED_MODULE_1__.isEqual)(inputSettings, savedInputSettings);
  },
  /**
   * Indicates whether the provided user input setting has changed from what is saved.
   *
   * @since 1.93.0
   *
   * @param {Object} state   Data store's state.
   * @param {string} setting The setting we want to check for saved changes.
   * @return {boolean} True if the settings have changed, false otherwise.
   */
  hasUserInputSettingChanged(state, setting) {
    invariant__WEBPACK_IMPORTED_MODULE_0___default()(setting, 'setting is required.');
    return baseSelectors.haveUserInputSettingsChanged(state, [setting]);
  }
};
const store = (0,googlesitekit_data__WEBPACK_IMPORTED_MODULE_3__.combineStores)(fetchGetUserInputSettingsStore, fetchSaveUserInputSettingsStore, {
  initialState: baseInitialState,
  actions: baseActions,
  reducer: baseReducer,
  resolvers: baseResolvers,
  selectors: baseSelectors
});
const initialState = store.initialState;
const actions = store.actions;
const controls = store.controls;
const reducer = store.reducer;
const resolvers = store.resolvers;
const selectors = store.selectors;
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (store);

/***/ }),

/***/ "./js/googlesitekit/datastore/util/permissions.js":
/*!********************************************************!*\
  !*** ./js/googlesitekit/datastore/util/permissions.js ***!
  \********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   getMetaCapabilityPropertyName: () => (/* binding */ getMetaCapabilityPropertyName)
/* harmony export */ });
/**
 * `core/user` data store: permission utils.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Returns the property name for a meta capability, given the capability name and arguments.
 *
 * @since 1.74.0
 *
 * @param {string} capability Meta capability name.
 * @param {...any} args       Meta capability arguments.
 * @return {string} Meta capability property name.
 */
function getMetaCapabilityPropertyName(capability, ...args) {
  return `${capability}::${JSON.stringify(args)}`;
}

/***/ }),

/***/ "./js/googlesitekit/modules/datastore/constants.js":
/*!*********************************************************!*\
  !*** ./js/googlesitekit/modules/datastore/constants.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CORE_MODULES: () => (/* binding */ CORE_MODULES),
/* harmony export */   ERROR_CODE_INSUFFICIENT_MODULE_DEPENDENCIES: () => (/* binding */ ERROR_CODE_INSUFFICIENT_MODULE_DEPENDENCIES)
/* harmony export */ });
/**
 * `core/modules` data store: constants.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const CORE_MODULES = 'core/modules';
const ERROR_CODE_INSUFFICIENT_MODULE_DEPENDENCIES = 'insufficient_module_dependencies';

/***/ }),

/***/ "./js/googlesitekit/widgets/datastore/constants.js":
/*!*********************************************************!*\
  !*** ./js/googlesitekit/widgets/datastore/constants.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CORE_WIDGETS: () => (/* binding */ CORE_WIDGETS),
/* harmony export */   WIDGET_AREA_STYLES: () => (/* binding */ WIDGET_AREA_STYLES),
/* harmony export */   WIDGET_WIDTHS: () => (/* binding */ WIDGET_WIDTHS)
/* harmony export */ });
/**
 * `core/widgets` data store: constants.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const WIDGET_AREA_STYLES = {
  BOXES: 'boxes',
  COMPOSITE: 'composite'
};
const WIDGET_WIDTHS = {
  QUARTER: 'quarter',
  HALF: 'half',
  FULL: 'full'
};
const CORE_WIDGETS = 'core/widgets';

/***/ }),

/***/ "./js/modules/analytics-4/datastore/constants.js":
/*!*******************************************************!*\
  !*** ./js/modules/analytics-4/datastore/constants.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ACCOUNT_CREATE: () => (/* binding */ ACCOUNT_CREATE),
/* harmony export */   AUDIENCE_FILTER_CLAUSE_TYPE_ENUM: () => (/* binding */ AUDIENCE_FILTER_CLAUSE_TYPE_ENUM),
/* harmony export */   AUDIENCE_FILTER_SCOPE_ENUM: () => (/* binding */ AUDIENCE_FILTER_SCOPE_ENUM),
/* harmony export */   AUDIENCE_ITEM_NEW_BADGE_SLUG_PREFIX: () => (/* binding */ AUDIENCE_ITEM_NEW_BADGE_SLUG_PREFIX),
/* harmony export */   AUDIENCE_SEGMENTATION_SETUP_FORM: () => (/* binding */ AUDIENCE_SEGMENTATION_SETUP_FORM),
/* harmony export */   AUDIENCE_TILE_CUSTOM_DIMENSION_CREATE: () => (/* binding */ AUDIENCE_TILE_CUSTOM_DIMENSION_CREATE),
/* harmony export */   AUDIENCE_TYPE_SORT_ORDER: () => (/* binding */ AUDIENCE_TYPE_SORT_ORDER),
/* harmony export */   CONVERSION_REPORTING_LEAD_EVENTS: () => (/* binding */ CONVERSION_REPORTING_LEAD_EVENTS),
/* harmony export */   CUSTOM_DIMENSION_DEFINITIONS: () => (/* binding */ CUSTOM_DIMENSION_DEFINITIONS),
/* harmony export */   DATE_RANGE_OFFSET: () => (/* binding */ DATE_RANGE_OFFSET),
/* harmony export */   EDIT_SCOPE: () => (/* binding */ EDIT_SCOPE),
/* harmony export */   ENHANCED_MEASUREMENT_ENABLED: () => (/* binding */ ENHANCED_MEASUREMENT_ENABLED),
/* harmony export */   ENHANCED_MEASUREMENT_FORM: () => (/* binding */ ENHANCED_MEASUREMENT_FORM),
/* harmony export */   ENHANCED_MEASUREMENT_SHOULD_DISMISS_ACTIVATION_BANNER: () => (/* binding */ ENHANCED_MEASUREMENT_SHOULD_DISMISS_ACTIVATION_BANNER),
/* harmony export */   ENUM_CONVERSION_EVENTS: () => (/* binding */ ENUM_CONVERSION_EVENTS),
/* harmony export */   FORM_ACCOUNT_CREATE: () => (/* binding */ FORM_ACCOUNT_CREATE),
/* harmony export */   FORM_CUSTOM_DIMENSIONS_CREATE: () => (/* binding */ FORM_CUSTOM_DIMENSIONS_CREATE),
/* harmony export */   FORM_SETUP: () => (/* binding */ FORM_SETUP),
/* harmony export */   GTM_SCOPE: () => (/* binding */ GTM_SCOPE),
/* harmony export */   MAX_WEBDATASTREAMS_PER_BATCH: () => (/* binding */ MAX_WEBDATASTREAMS_PER_BATCH),
/* harmony export */   MODULES_ANALYTICS_4: () => (/* binding */ MODULES_ANALYTICS_4),
/* harmony export */   PROPERTY_CREATE: () => (/* binding */ PROPERTY_CREATE),
/* harmony export */   PROVISIONING_SCOPE: () => (/* binding */ PROVISIONING_SCOPE),
/* harmony export */   RESOURCE_TYPES: () => (/* binding */ RESOURCE_TYPES),
/* harmony export */   RESOURCE_TYPE_AUDIENCE: () => (/* binding */ RESOURCE_TYPE_AUDIENCE),
/* harmony export */   RESOURCE_TYPE_CUSTOM_DIMENSION: () => (/* binding */ RESOURCE_TYPE_CUSTOM_DIMENSION),
/* harmony export */   RESOURCE_TYPE_PROPERTY: () => (/* binding */ RESOURCE_TYPE_PROPERTY),
/* harmony export */   SITE_KIT_AUDIENCE_DEFINITIONS: () => (/* binding */ SITE_KIT_AUDIENCE_DEFINITIONS),
/* harmony export */   UI_ACTIVE_ROW_INDEX: () => (/* binding */ UI_ACTIVE_ROW_INDEX),
/* harmony export */   UI_ALL_TRAFFIC_LOADED: () => (/* binding */ UI_ALL_TRAFFIC_LOADED),
/* harmony export */   UI_DIMENSION_COLOR: () => (/* binding */ UI_DIMENSION_COLOR),
/* harmony export */   UI_DIMENSION_NAME: () => (/* binding */ UI_DIMENSION_NAME),
/* harmony export */   UI_DIMENSION_VALUE: () => (/* binding */ UI_DIMENSION_VALUE),
/* harmony export */   WEBDATASTREAM_CREATE: () => (/* binding */ WEBDATASTREAM_CREATE)
/* harmony export */ });
/**
 * `modules/analytics-4` data store constants.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const MODULES_ANALYTICS_4 = 'modules/analytics-4';

// A special Account ID value used for the "Set up a new account" option.
const ACCOUNT_CREATE = 'account_create';

// A special Property ID value used for the "Set up a new property" option.
const PROPERTY_CREATE = 'property_create';
const WEBDATASTREAM_CREATE = 'webdatastream_create';
const FORM_SETUP = 'analyticsSetup';
const MAX_WEBDATASTREAMS_PER_BATCH = 10;

// Date range offset days for Analytics 4 report requests.
const DATE_RANGE_OFFSET = 1;
const GTM_SCOPE = 'https://www.googleapis.com/auth/tagmanager.readonly';
const ENHANCED_MEASUREMENT_FORM = 'enhanced-measurement-form';
const ENHANCED_MEASUREMENT_ENABLED = 'enhanced-measurement-enabled';
const ENHANCED_MEASUREMENT_SHOULD_DISMISS_ACTIVATION_BANNER = 'enhanced-measurement-should-dismiss-activation-banner';

// Form ID for the account creation form.
const FORM_ACCOUNT_CREATE = 'analyticsAccountCreate';
const FORM_CUSTOM_DIMENSIONS_CREATE = 'analyticsCustomDimensionsCreate';

// OAuth scope required for provisioning a Google Analytics account.
const PROVISIONING_SCOPE = 'https://www.googleapis.com/auth/analytics.provision';
const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit';

// Dashboard widget constants.
const UI_DIMENSION_NAME = 'dashboardAllTrafficWidgetDimensionName';
const UI_DIMENSION_COLOR = 'dashboardAllTrafficWidgetDimensionColor';
const UI_DIMENSION_VALUE = 'dashboardAllTrafficWidgetDimensionValue';
const UI_ACTIVE_ROW_INDEX = 'dashboardAllTrafficWidgetActiveRowIndex';
const UI_ALL_TRAFFIC_LOADED = 'dashboardAllTrafficWidgetLoaded';

// Note: names and descriptions are not translated as these are not surfaced in Site Kit
// and are also subject to hard limits on the length which would be unpredictable if translated.
// See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/properties.customDimensions#CustomDimension
const CUSTOM_DIMENSION_DEFINITIONS = {
  googlesitekit_post_date: {
    parameterName: 'googlesitekit_post_date',
    displayName: 'WordPress Post Date',
    description: 'Created by Site Kit: Date when a post was published',
    scope: 'EVENT'
  },
  googlesitekit_post_author: {
    parameterName: 'googlesitekit_post_author',
    displayName: 'WordPress Post Author',
    description: 'Created by Site Kit: WordPress name of the post author',
    scope: 'EVENT'
  },
  googlesitekit_post_categories: {
    parameterName: 'googlesitekit_post_categories',
    displayName: 'WordPress Post Categories',
    description: 'Created by Site Kit: Names of categories assigned to a post',
    scope: 'EVENT'
  },
  googlesitekit_post_type: {
    parameterName: 'googlesitekit_post_type',
    displayName: 'WordPress Post Type',
    description: 'Created by Site Kit: Content type of a post',
    scope: 'EVENT'
  }
};
const ENUM_CONVERSION_EVENTS = {
  ADD_TO_CART: 'add_to_cart',
  PURCHASE: 'purchase',
  SUBMIT_LEAD_FORM: 'submit_lead_form',
  GENERATE_LEAD: 'generate_lead',
  CONTACT: 'contact'
};
const CONVERSION_REPORTING_LEAD_EVENTS = [ENUM_CONVERSION_EVENTS.CONTACT, ENUM_CONVERSION_EVENTS.GENERATE_LEAD, ENUM_CONVERSION_EVENTS.SUBMIT_LEAD_FORM];

// Audience enums.
const AUDIENCE_FILTER_CLAUSE_TYPE_ENUM = {
  AUDIENCE_CLAUSE_TYPE_UNSPECIFIED: 'AUDIENCE_CLAUSE_TYPE_UNSPECIFIED',
  INCLUDE: 'INCLUDE',
  EXCLUDE: 'EXCLUDE'
};
const AUDIENCE_FILTER_SCOPE_ENUM = {
  AUDIENCE_FILTER_SCOPE_UNSPECIFIED: 'AUDIENCE_FILTER_SCOPE_UNSPECIFIED',
  AUDIENCE_FILTER_SCOPE_WITHIN_SAME_EVENT: 'AUDIENCE_FILTER_SCOPE_WITHIN_SAME_EVENT',
  AUDIENCE_FILTER_SCOPE_WITHIN_SAME_SESSION: 'AUDIENCE_FILTER_SCOPE_WITHIN_SAME_SESSION',
  AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS: 'AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS'
};
const SITE_KIT_AUDIENCE_DEFINITIONS = {
  'new-visitors': {
    description: 'People who visited the site for the first time',
    displayName: 'New visitors',
    membershipDurationDays: -1,
    // The longest duration, 540 days.
    filterClauses: [{
      clauseType: 'INCLUDE',
      simpleFilter: {
        scope: 'AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS',
        filterExpression: {
          andGroup: {
            filterExpressions: [{
              orGroup: {
                filterExpressions: [{
                  dimensionOrMetricFilter: {
                    fieldName: 'newVsReturning',
                    stringFilter: {
                      matchType: 'EXACT',
                      value: 'new'
                    }
                  }
                }]
              }
            }, {
              orGroup: {
                filterExpressions: [{
                  notExpression: {
                    dimensionOrMetricFilter: {
                      fieldName: 'groupId',
                      stringFilter: {
                        matchType: 'EXACT',
                        value: 'created_by_googlesitekit:new_visitors'
                      }
                    }
                  }
                }]
              }
            }]
          }
        }
      }
    }]
  },
  'returning-visitors': {
    description: 'People who have visited your site at least once before',
    displayName: 'Returning visitors',
    membershipDurationDays: -1,
    // The longest duration, 540 days.
    filterClauses: [{
      clauseType: 'INCLUDE',
      simpleFilter: {
        scope: 'AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS',
        filterExpression: {
          andGroup: {
            filterExpressions: [{
              orGroup: {
                filterExpressions: [{
                  dimensionOrMetricFilter: {
                    fieldName: 'newVsReturning',
                    stringFilter: {
                      matchType: 'EXACT',
                      value: 'returning'
                    }
                  }
                }]
              }
            }, {
              orGroup: {
                filterExpressions: [{
                  notExpression: {
                    dimensionOrMetricFilter: {
                      fieldName: 'groupId',
                      stringFilter: {
                        matchType: 'EXACT',
                        value: 'created_by_googlesitekit:returning_visitors'
                      }
                    }
                  }
                }]
              }
            }]
          }
        }
      }
    }]
  }
};
const AUDIENCE_SEGMENTATION_SETUP_FORM = 'audiencePermissionsSetup';
const AUDIENCE_TILE_CUSTOM_DIMENSION_CREATE = 'audienceTileCustomDimensionCreate';
const AUDIENCE_TYPE_SORT_ORDER = {
  USER_AUDIENCE: 0,
  SITE_KIT_AUDIENCE: 1,
  DEFAULT_AUDIENCE: 2
};
const AUDIENCE_ITEM_NEW_BADGE_SLUG_PREFIX = 'audience-selection-panel-expirable-new-badge-';
const RESOURCE_TYPE_AUDIENCE = 'audience';
const RESOURCE_TYPE_CUSTOM_DIMENSION = 'customDimension';
const RESOURCE_TYPE_PROPERTY = 'property';
const RESOURCE_TYPES = [RESOURCE_TYPE_AUDIENCE, RESOURCE_TYPE_CUSTOM_DIMENSION, RESOURCE_TYPE_PROPERTY];

/***/ }),

/***/ "./js/util/chart.js":
/*!**************************!*\
  !*** ./js/util/chart.js ***!
  \**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   calculateDifferenceBetweenChartValues: () => (/* binding */ calculateDifferenceBetweenChartValues),
/* harmony export */   getChartDifferenceArrow: () => (/* binding */ getChartDifferenceArrow),
/* harmony export */   isSingleSlice: () => (/* binding */ isSingleSlice)
/* harmony export */ });
/* harmony import */ var _wordpress_element__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @wordpress/element */ "../node_modules/@wordpress/element/build-module/serialize.js");
/* harmony import */ var _js_components_ChangeArrow__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/js/components/ChangeArrow */ "./js/components/ChangeArrow.js");
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react/jsx-runtime */ "../node_modules/react/jsx-runtime.js");
/**
 * Utility functions for charts.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */


/**
 * Internal dependencies
 */


/**
 * Gets the up/down SVG arrow for Google Chart tooltips.
 *
 * @since 1.30.0
 *
 * @param {number}  difference            The difference which can be positive or negative.
 * @param {string}  [options]             Options to be passed to the ChangeArrow component.
 * @param {boolean} [options.invertColor] Whether we need to reverse the +/- colors of the arrow.
 * @return {string} SVG for the +/- difference.
 */

function getChartDifferenceArrow(difference, options = {}) {
  if (Number.isNaN(Number(difference))) {
    return '';
  }
  const {
    invertColor = false
  } = options;
  return (0,_wordpress_element__WEBPACK_IMPORTED_MODULE_2__["default"])(/*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_1__.jsx)(_js_components_ChangeArrow__WEBPACK_IMPORTED_MODULE_0__["default"], {
    direction: difference > 0 ? 'up' : 'down',
    invertColor: invertColor
  }));
}

/**
 * Checks if there is a single row of data or one row is contributing 100% of the total for a given dimension.
 *
 * @since 1.31.0
 *
 * @param {Array.<Object>} report An array of report data objects.
 * @return {(boolean|undefined)} Returns undefined if report is undefined, true/false for the above conditions.
 */
function isSingleSlice(report) {
  if (report === undefined) {
    return undefined;
  }
  if (report?.[0]?.data?.rows?.length === 1 || report?.[0]?.data?.rows?.[0]?.metrics?.[0]?.values?.[0] === report?.[0]?.data?.totals?.[0]?.values?.[0]) {
    return true;
  }
  return false;
}

/**
 * Calculates difference between two chart values.
 *
 * @since 1.48.0
 *
 * @param {number} currentValue  Current chart value.
 * @param {number} previousValue Previous chart value.
 * @return {number} The difference.
 */
function calculateDifferenceBetweenChartValues(currentValue, previousValue) {
  if (currentValue > 0 && previousValue > 0) {
    return currentValue / previousValue - 1;
  }
  if (currentValue > 0) {
    return 1;
  }
  if (previousValue > 0) {
    return -1;
  }
  return 0;
}

/***/ }),

/***/ "./js/util/convert-time.js":
/*!*********************************!*\
  !*** ./js/util/convert-time.js ***!
  \*********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   convertDateStringToUNIXTimestamp: () => (/* binding */ convertDateStringToUNIXTimestamp),
/* harmony export */   convertSecondsToArray: () => (/* binding */ convertSecondsToArray)
/* harmony export */ });
/**
 * Time related utility functions.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Converts seconds into an array with the following values [HH, MM, SS, MS] as described below.
 * HH: hours.
 * MM: minutes.
 * SS: seconds.
 * MS: milliseconds.
 *
 * For example, passing 196.385 returns [ 0, 3, 16, 385 ].
 *
 * @since 1.27.0
 *
 * @param {number} seconds The number of seconds.
 * @return {Array} Array containing the hours, minutes, seconds and milliseconds.
 */
function convertSecondsToArray(seconds) {
  seconds = parseFloat(seconds);
  if (isNaN(seconds) || 0 === seconds) {
    return [0, 0, 0, 0];
  }
  return [Math.floor(seconds / 60 / 60), Math.floor(seconds / 60 % 60), Math.floor(seconds % 60), Math.floor(seconds * 1000) - Math.floor(seconds) * 1000];
}

/**
 * Converts Date time string into UNIX timestamp in milliseconds.
 *
 * For example, passing "2014-10-02T15:01:23Z" returns 1412262083000.
 *
 * @since 1.116.0
 *
 * @param {string} dateStringValue The date time string.
 * @return {number} UNIX timestamp in milliseconds.
 */
function convertDateStringToUNIXTimestamp(dateStringValue) {
  const unixTimestamp = dateStringValue && !Number.isInteger(dateStringValue) ?
  // Valid use of `new Date()` with an argument, because this should only
  // be passed full time strings, not `YYYY-MM-DD` style dates.
  //
  // See: https://github.com/google/site-kit-wp/pull/9459#discussion_r1790660073
  // eslint-disable-next-line sitekit/no-direct-date
  new Date(dateStringValue).getTime() : dateStringValue;
  if (isNaN(unixTimestamp) || !unixTimestamp) {
    return 0;
  }
  return unixTimestamp;
}

/***/ }),

/***/ "./js/util/dates.js":
/*!**************************!*\
  !*** ./js/util/dates.js ***!
  \**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DAY_IN_SECONDS: () => (/* binding */ DAY_IN_SECONDS),
/* harmony export */   HOUR_IN_SECONDS: () => (/* binding */ HOUR_IN_SECONDS),
/* harmony export */   INVALID_DATE_INSTANCE_ERROR: () => (/* binding */ INVALID_DATE_INSTANCE_ERROR),
/* harmony export */   INVALID_DATE_RANGE_ERROR: () => (/* binding */ INVALID_DATE_RANGE_ERROR),
/* harmony export */   INVALID_DATE_STRING_ERROR: () => (/* binding */ INVALID_DATE_STRING_ERROR),
/* harmony export */   MINUTE_IN_SECONDS: () => (/* binding */ MINUTE_IN_SECONDS),
/* harmony export */   MONTH_IN_SECONDS: () => (/* binding */ MONTH_IN_SECONDS),
/* harmony export */   WEEK_IN_SECONDS: () => (/* binding */ WEEK_IN_SECONDS),
/* harmony export */   dateSub: () => (/* binding */ dateSub),
/* harmony export */   getAvailableDateRanges: () => (/* binding */ getAvailableDateRanges),
/* harmony export */   getCurrentDateRangeDayCount: () => (/* binding */ getCurrentDateRangeDayCount),
/* harmony export */   getDateString: () => (/* binding */ getDateString),
/* harmony export */   getPreviousDate: () => (/* binding */ getPreviousDate),
/* harmony export */   isValidDateRange: () => (/* binding */ isValidDateRange),
/* harmony export */   isValidDateString: () => (/* binding */ isValidDateString),
/* harmony export */   stringToDate: () => (/* binding */ stringToDate)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n");
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__);
/**
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * WordPress dependencies
 */

const INVALID_DATE_INSTANCE_ERROR = 'Date param must construct to a valid date instance or be a valid date instance itself.';
const INVALID_DATE_STRING_ERROR = 'Invalid dateString parameter, it must be a string.';
const INVALID_DATE_RANGE_ERROR = 'Invalid date range, it must be a string with the format "last-x-days".';
const MINUTE_IN_SECONDS = 60;
const HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS;
const DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS;
const WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS;
const MONTH_IN_SECONDS = 30 * DAY_IN_SECONDS;

/**
 * Gets the hash of available date ranges.
 *
 * @since 1.12.0
 *
 * @return {Object} The object hash where every key is a date range slug, and the value is an object with the date range slug and its translation.
 */
function getAvailableDateRanges() {
  function label(days) {
    return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(/* translators: %s: number of days */
    (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__._n)('Last %s day', 'Last %s days', days, 'google-site-kit'), days);
  }
  return {
    'last-7-days': {
      slug: 'last-7-days',
      label: label(7),
      days: 7
    },
    'last-14-days': {
      slug: 'last-14-days',
      label: label(14),
      days: 14
    },
    'last-28-days': {
      slug: 'last-28-days',
      label: label(28),
      days: 28
    },
    'last-90-days': {
      slug: 'last-90-days',
      label: label(90),
      days: 90
    }
  };
}

/**
 * Gets the current dateRange day count.
 *
 * @since 1.19.0
 * @since 1.26.0 `dateRange` is now a required argument.
 *
 * @param {string} dateRange The date range slug.
 * @return {number} The number of days in the range.
 */
function getCurrentDateRangeDayCount(dateRange) {
  const daysMatch = dateRange.match(/last-(\d+)-days/);
  if (daysMatch && daysMatch[1]) {
    return parseInt(daysMatch[1], 10);
  }
  throw new Error('Unrecognized date range slug.');
}

/**
 * Asserts whether a given date string is valid or invalid.
 *
 * @since 1.18.0
 *
 * @param {string} dateString Date string to be asserted against. Defaults to an empty string.
 * @return {boolean}          True if the given date string is valid.
 */
function isValidDateString(dateString = '') {
  if (!(0,lodash__WEBPACK_IMPORTED_MODULE_1__.isString)(dateString)) {
    return false;
  }
  const dateArray = dateString.split('-');
  if (dateArray.length !== 3) {
    return false;
  }

  // Valid use of `new Date()`, constructing a new date from the string.
  // eslint-disable-next-line sitekit/no-direct-date
  const date = new Date(dateString);
  return (0,lodash__WEBPACK_IMPORTED_MODULE_1__.isDate)(date) && !isNaN(date);
}

/**
 * Parses the given Date instance and returns a date string (YYYY-MM-DD).
 *
 * @since 1.18.0
 * @since 1.85.0 Updated the function signature to only accept a Date argument.
 *
 * @param {Date} date Date to parse into a string.
 * @return {string}                 The parsed date string (YYYY-MM-DD).
 */
function getDateString(date) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()((0,lodash__WEBPACK_IMPORTED_MODULE_1__.isDate)(date) && !isNaN(date), INVALID_DATE_INSTANCE_ERROR);
  const month = `${date.getMonth() + 1}`;
  const day = `${date.getDate()}`;
  const year = date.getFullYear();
  return [year, month.length < 2 ? `0${month}` : month, day.length < 2 ? `0${day}` : day].join('-');
}

/**
 * Converts a valid date string to a Date instance.
 *
 * @since 1.38.0
 *
 * @param {string} dateString The date string to parse.
 * @return {Date} Date instance.
 */
function stringToDate(dateString) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(isValidDateString(dateString), INVALID_DATE_STRING_ERROR);

  /**
   * Split date into explicit parts rather than pass directly into date constructor
   * to avoid timezone issues caused by parsing as UTC. Ensures date is accurate for
   * the user's local time, otherwise has a chance to return a different day than was
   * passed in depending on timezone.
   */
  const [year, month, day] = dateString.split('-');
  return new Date(year, month - 1, day);
}

/**
 * Parses the given date and returns the previous date (daysBefore).
 *
 * @since 1.18.0
 *
 * @param {string} relativeDate Date string (YYYY-MM-DD) to subtract days from.
 * @param {number} daysBefore   Number of days to subtract from relativeDate.
 * @return {string}             The date string (YYYY-MM-DD) for the previous date.
 */
function getPreviousDate(relativeDate, daysBefore) {
  return getDateString(dateSub(relativeDate, daysBefore * DAY_IN_SECONDS));
}

/**
 * Asserts whether a given dateRange string is valid or invalid.
 *
 * @since 1.18.0
 *
 * @param {string} dateRange Date string to be asserted against. Defaults to an empty string.
 * @return {boolean}          True if the given dateRange string is valid.
 */
function isValidDateRange(dateRange) {
  const parts = dateRange.split('-');
  return parts.length === 3 && parts[0] === 'last' && !Number.isNaN(parts[1]) && !Number.isNaN(parseFloat(parts[1])) && parts[2] === 'days';
}

/**
 * Subtracts duration from the prodived date and returns it.
 *
 * @since 1.132.0
 *
 * @param {Date|string} relativeDate Date string (YYYY-MM-DD) or date object to subtract duration from.
 * @param {number}      duration     The duration in seconds to subtract from relativeDate.
 * @return {Date} Resulting date.
 */
function dateSub(relativeDate, duration) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(isValidDateString(relativeDate) || (0,lodash__WEBPACK_IMPORTED_MODULE_1__.isDate)(relativeDate) && !isNaN(relativeDate), INVALID_DATE_STRING_ERROR);
  const timestamp = isValidDateString(relativeDate) ? Date.parse(relativeDate) : relativeDate.getTime();

  // Valid use of `new Date()` using calculations.
  // eslint-disable-next-line sitekit/no-direct-date
  return new Date(timestamp - duration * 1000);
}

/***/ }),

/***/ "./js/util/escape-uri.ts":
/*!*******************************!*\
  !*** ./js/util/escape-uri.ts ***!
  \*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   escapeURI: () => (/* binding */ escapeURI)
/* harmony export */ });
/**
 * Escape URI components utility.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Escapes URI components in a template string as a tag function.
 *
 * @example
 * ```
 * // Escape a redirect url:
 * const redirectTo = 'http://localhost/admin/';
 * const loginUrl = escapeURI`http://localhost/login?redirect=${ redirectTo }`;
 * ```
 * @since 1.11.0
 *
 * @param strings The array of static strings in the template.
 * @param values  The array of expressions used in the template.
 * @return The escaped URI.
 */
function escapeURI(
/**
 * The array of static strings in the template.
 */
strings,
/**
 * The array of expressions used in the template.
 */
...values) {
  return strings.reduce((acc, string, idx) => {
    return acc + string + encodeURIComponent(values[idx] || '');
  }, '');
}

/***/ }),

/***/ "./js/util/i18n.js":
/*!*************************!*\
  !*** ./js/util/i18n.js ***!
  \*************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createDurationFormat: () => (/* binding */ createDurationFormat),
/* harmony export */   expandNumFmtOptions: () => (/* binding */ expandNumFmtOptions),
/* harmony export */   getLocale: () => (/* binding */ getLocale),
/* harmony export */   listFormat: () => (/* binding */ listFormat),
/* harmony export */   numFmt: () => (/* binding */ numFmt),
/* harmony export */   numberFormat: () => (/* binding */ numberFormat),
/* harmony export */   prepareForReadableLargeNumber: () => (/* binding */ prepareForReadableLargeNumber),
/* harmony export */   readableLargeNumber: () => (/* binding */ readableLargeNumber)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! memize */ "../node_modules/memize/index.js");
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(memize__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n");
/* harmony import */ var _wordpress_i18n__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__);
/**
 * Internationalization Utilities.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */



/**
 * WordPress dependencies
 */


/**
 * Converts seconds to a display ready string indicating
 * the number of hours, minutes and seconds that have elapsed.
 *
 * For example, passing 65 returns '1m 5s'.
 *
 * @since 1.0.0
 * @since 1.28.0 Refactored and renamed to improve localization.
 * @private
 *
 * @param {number}                     durationInSeconds The number of seconds.
 * @param {(Intl.NumberFormatOptions)} [options]         Optional formatting options.
 * @return {string} Human readable string indicating time elapsed.
 */
function durationFormat(durationInSeconds, options = {}) {
  const {
    formatUnit,
    formatDecimal
  } = createDurationFormat(durationInSeconds, options);
  try {
    // Some browsers, e.g. Safari, throw a RangeError when options.style is
    // not one of decimal, percent, or currency.
    return formatUnit();
  } catch {
    // Fallback to XXh YYm ZZs using localized decimals with hardcoded units.
    return formatDecimal();
  }
}

/**
 * Converts seconds to a display ready string indicating
 * the number of hours, minutes and seconds that have elapsed
 * in ISO format - HH:mm:ss.
 *
 * If the duration is less than an hour, the HH part of the string
 * is truncated.
 * For example, passing 65 returns '01:05'.
 * Passing 5400 returns '01:30:00'.
 *
 * @since 1.111.0
 * @private
 *
 * @param {number} durationInSeconds The number of seconds.
 * @return {string} Human readable string indicating time elapsed.
 */
function durationISOFormat(durationInSeconds) {
  let {
    hours,
    minutes,
    seconds
  } = parseDuration(durationInSeconds);
  seconds = ('0' + seconds).slice(-2);
  minutes = ('0' + minutes).slice(-2);
  hours = ('0' + hours).slice(-2);
  return hours === '00' ? `${minutes}:${seconds}` : `${hours}:${minutes}:${seconds}`;
}

/**
 * Parses the duration in seconds into hours, minutes and seconds.
 *
 * @since 1.111.0
 * @private
 *
 * @param {number} durationInSeconds The number of seconds.
 * @return {Object} Number of hours, minutes and seconds equivalent
 * to the given duration in seconds.
 */
function parseDuration(durationInSeconds) {
  durationInSeconds = parseInt(durationInSeconds, 10);
  if (Number.isNaN(durationInSeconds)) {
    durationInSeconds = 0;
  }
  const hours = Math.floor(durationInSeconds / 60 / 60);
  const minutes = Math.floor(durationInSeconds / 60 % 60);
  const seconds = Math.floor(durationInSeconds % 60);
  return {
    hours,
    minutes,
    seconds
  };
}

/**
 * Creates duration formatting utilities.
 *
 * Not intended to be used directly.
 * Use `numFmt( number, { style: 'duration' } )` instead.
 *
 * @since 1.29.0
 * @private
 *
 * @param {number} durationInSeconds Duration to format.
 * @param {Object} [options]         Formatting options.
 * @return {Object} Formatting functions.
 */
function createDurationFormat(durationInSeconds, options = {}) {
  const {
    hours,
    minutes,
    seconds
  } = parseDuration(durationInSeconds);
  return {
    hours,
    minutes,
    seconds,
    formatUnit() {
      const {
        unitDisplay = 'short',
        ...restOptions
      } = options;
      const commonOptions = {
        unitDisplay,
        ...restOptions,
        style: 'unit'
      };
      if (durationInSeconds === 0) {
        return numberFormat(seconds, {
          ...commonOptions,
          unit: 'second'
        });
      }
      return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(/* translators: 1: formatted seconds, 2: formatted minutes, 3: formatted hours */
      (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__._x)('%3$s %2$s %1$s', 'duration of time: hh mm ss', 'google-site-kit'), seconds ? numberFormat(seconds, {
        ...commonOptions,
        unit: 'second'
      }) : '', minutes ? numberFormat(minutes, {
        ...commonOptions,
        unit: 'minute'
      }) : '', hours ? numberFormat(hours, {
        ...commonOptions,
        unit: 'hour'
      }) : '').trim();
    },
    /**
     * Formats the duration using integers and translatable strings.
     * This is only used as a fallback when the above `formatUnit` fails.
     *
     * @since 1.29.0
     *
     * @return {string} Formatted duration.
     */
    formatDecimal() {
      const formattedSeconds = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
      // translators: %s: number of seconds with "s" as the abbreviated unit.
      (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%ds', 'google-site-kit'), seconds);
      if (durationInSeconds === 0) {
        return formattedSeconds;
      }
      const formattedMinutes = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
      // translators: %s: number of minutes with "m" as the abbreviated unit.
      (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%dm', 'google-site-kit'), minutes);
      const formattedHours = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
      // translators: %s: number of hours with "h" as the abbreviated unit.
      (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%dh', 'google-site-kit'), hours);
      return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(/* translators: 1: formatted seconds, 2: formatted minutes, 3: formatted hours */
      (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__._x)('%3$s %2$s %1$s', 'duration of time: hh mm ss', 'google-site-kit'), seconds ? formattedSeconds : '', minutes ? formattedMinutes : '', hours ? formattedHours : '').trim();
    }
  };
}

/**
 * Prepares a number to be used in readableLargeNumber.
 *
 * @since 1.7.0
 *
 * @param {number} number The large number to prepare.
 * @return {number} The prepared number.
 */
function prepareForReadableLargeNumber(number) {
  if (1000000 <= number) {
    return Math.round(number / 100000) / 10;
  }
  if (10000 <= number) {
    return Math.round(number / 1000);
  }
  if (1000 <= number) {
    return Math.round(number / 100) / 10;
  }
  return number;
}

/**
 * Formats a large number for shortened display.
 *
 * @since 1.0.0
 *
 * @param {number} number The large number to format.
 * @return {string} The formatted number.
 */
function readableLargeNumber(number) {
  const withSingleDecimal = {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1
  };

  // Numbers over 1,000,000 round normally and display a single decimal unless the decimal is 0.
  if (1000000 <= number) {
    return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
    // translators: %s: an abbreviated number in millions.
    (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%sM', 'google-site-kit'), numberFormat(prepareForReadableLargeNumber(number), number % 10 === 0 ? {} : withSingleDecimal));
  }

  // Numbers between 10,000 and 1,000,000 round normally and have no decimals
  if (10000 <= number) {
    return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
    // translators: %s: an abbreviated number in thousands.
    (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%sK', 'google-site-kit'), numberFormat(prepareForReadableLargeNumber(number)));
  }

  // Numbers between 1,000 and 10,000 round normally and display a single decimal unless the decimal is 0.
  if (1000 <= number) {
    return (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.sprintf)(
    // translators: %s: an abbreviated number in thousands.
    (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)('%sK', 'google-site-kit'), numberFormat(prepareForReadableLargeNumber(number), number % 10 === 0 ? {} : withSingleDecimal));
  }
  return numberFormat(number, {
    signDisplay: 'never',
    maximumFractionDigits: 1
  });
}

/**
 * Parses formatting options and returns an object with options for selected formatting.
 *
 * @since 1.103.0
 *
 * @param {(Intl.NumberFormatOptions|string)} options Formatting options or unit shorthand. Possible shorthand values are '%', 's', or a currency code.
 * @return {Object} Formatting options.
 */
function expandNumFmtOptions(options) {
  let formatOptions = {};

  // Expand shorthand values for units.
  if ('%' === options) {
    formatOptions = {
      style: 'percent',
      maximumFractionDigits: 2
    };
  } else if ('s' === options) {
    formatOptions = {
      style: 'duration',
      unitDisplay: 'narrow'
    };
  } else if (!!options && typeof options === 'string') {
    formatOptions = {
      style: 'currency',
      currency: options
    };
  } else if ((0,lodash__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(options)) {
    formatOptions = {
      ...options
    };
  }
  return formatOptions;
}

/**
 * Formats a number with unit using the JS Internationalization Number Format API.
 *
 * In addition to the supported 'style' values of the lower-level `numberFormat` function, this function
 * supports two additional 'style' values 'metric' and 'duration' (expects a number in seconds).
 *
 * Another differentiation in behavior is that by default the function will use 'metric' formatting instead
 * of 'decimal' formatting.
 *
 * @since 1.24.0
 *
 * @param {number|string}                     number    The number to format.
 * @param {(Intl.NumberFormatOptions|string)} [options] Formatting options or unit shorthand.
 *                                                      Possible shorthand values are '%', 's',
 *                                                      or a currency code.
 * @return {string} The formatted number.
 */
function numFmt(number, options = {}) {
  // Cast parsable values to numeric types.
  number = (0,lodash__WEBPACK_IMPORTED_MODULE_0__.isFinite)(number) ? number : Number(number);
  if (!(0,lodash__WEBPACK_IMPORTED_MODULE_0__.isFinite)(number)) {
    // eslint-disable-next-line no-console
    console.warn('Invalid number', number, typeof number);
    number = 0;
  }
  const formatOptions = expandNumFmtOptions(options);
  const {
    style = 'metric'
  } = formatOptions; // Note: `metric` is our custom, default style.

  if ('metric' === style) {
    return readableLargeNumber(number);
  }
  if ('duration' === style) {
    return durationFormat(number, formatOptions);
  }
  if ('durationISO' === style) {
    return durationISOFormat(number);
  }
  return numberFormat(number, formatOptions);
}

// Warn once for a given message.
const warnOnce = memize__WEBPACK_IMPORTED_MODULE_1___default()(console.warn); // eslint-disable-line no-console

/**
 * Formats a number using the JS Internationalization Number Format API.
 *
 * @since 1.8.0
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/NumberFormat|`options` parameter} For all available formatting options.
 *
 * @param {number}                   number           The number to format.
 * @param {Intl.NumberFormatOptions} [options]        Formatting options.
 * @param {string}                   [options.locale] Locale to use for formatting. Defaults to current locale used by Site Kit.
 * @return {string} The formatted number.
 */
function numberFormat(number, options = {}) {
  const {
    locale = getLocale(),
    ...formatOptions
  } = options;
  try {
    /**
     * Per https://github.com/google/site-kit-wp/issues/3255 there have been issues with some versions of Safari
     * on some operating systems throwing issues with some parameters in the formatOptions.
     *
     * If an error is thrown, we remove some troublesome params from the formatOptions object and fallback to no formatting.
     *
     * This allows us to degrade somewhat gracefully without breaking the dashboard for users of unaffected browsers.
     */
    return new Intl.NumberFormat(locale, formatOptions).format(number);
  } catch (error) {
    warnOnce(`Site Kit numberFormat error: Intl.NumberFormat( ${JSON.stringify(locale)}, ${JSON.stringify(formatOptions)} ).format( ${typeof number} )`, error.message);
  }

  // Remove these key/values from formatOptions.
  const unstableFormatOptionValues = {
    currencyDisplay: 'narrow',
    currencySign: 'accounting',
    style: 'unit'
  };

  // Remove these keys from formatOptions irrespective of value.
  const unstableFormatOptions = ['signDisplay', 'compactDisplay'];
  const reducedFormatOptions = {};
  for (const [key, value] of Object.entries(formatOptions)) {
    if (unstableFormatOptionValues[key] && value === unstableFormatOptionValues[key]) {
      continue;
    }
    if (unstableFormatOptions.includes(key)) {
      continue;
    }
    reducedFormatOptions[key] = value;
  }
  try {
    return new Intl.NumberFormat(locale, reducedFormatOptions).format(number);
  } catch {
    return new Intl.NumberFormat(locale).format(number);
  }
}

/**
 * Flattens an array of strings into a string using the JS Internationalization List Format API.
 *
 * @since 1.23.0
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat|`options` parameter} For all available options.
 *
 * @param {Array}  list             The list to flatten.
 * @param {Object} [options]        Formatting options.
 * @param {string} [options.locale] Locale to use for formatting. Defaults to current locale used by Site Kit.
 * @param {string} [options.style]  Length of the formatted message. Defaults to long.
 * @param {string} [options.type]   Type of list. Defaults to 'conjunction' (A, B, and C).
 *                                  Also available 'disjunction' (A, B, or C)
 *                                  Also available 'unit' (5 pounds, 12 ounces)
 * @return {string} The flattened list.
 */
function listFormat(list, options = {}) {
  const {
    locale = getLocale(),
    style = 'long',
    type = 'conjunction'
  } = options;

  // Not all browsers support Intl.Listformat per
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#Browser_compatibility
  // We've seen that the built versions don't polyfill for the unsupported browsers (iOS/safari) so we provide a fallback.
  if (Intl.ListFormat) {
    const formatter = new Intl.ListFormat(locale, {
      style,
      type
    });
    return formatter.format(list);
  }

  /* translators: used between list items, there is a space after the comma. */
  const listSeparator = (0,_wordpress_i18n__WEBPACK_IMPORTED_MODULE_2__.__)(', ', 'google-site-kit');
  return list.join(listSeparator);
}

/**
 * Gets the current locale for use with browser APIs.
 *
 * @since 1.8.0
 *
 * @param {Object} _global The global window object.
 * @return {string} Current Site Kit locale if set, otherwise the current language set by the browser.
 *                  E.g. `en-US` or `de-DE`
 */
function getLocale(_global = __webpack_require__.g) {
  const siteKitLocale = (0,lodash__WEBPACK_IMPORTED_MODULE_0__.get)(_global, ['_googlesitekitLegacyData', 'locale']);
  if (siteKitLocale) {
    const matches = siteKitLocale.match(/^(\w{2})?(_)?(\w{2})/);
    if (matches && matches[0]) {
      return matches[0].replace(/_/g, '-');
    }
  }
  return _global.navigator.language;
}

/***/ }),

/***/ "./js/util/index.js":
/*!**************************!*\
  !*** ./js/util/index.js ***!
  \**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DAY_IN_SECONDS: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.DAY_IN_SECONDS),
/* harmony export */   HOUR_IN_SECONDS: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.HOUR_IN_SECONDS),
/* harmony export */   INVALID_DATE_INSTANCE_ERROR: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.INVALID_DATE_INSTANCE_ERROR),
/* harmony export */   INVALID_DATE_RANGE_ERROR: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.INVALID_DATE_RANGE_ERROR),
/* harmony export */   INVALID_DATE_STRING_ERROR: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.INVALID_DATE_STRING_ERROR),
/* harmony export */   MINUTE_IN_SECONDS: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.MINUTE_IN_SECONDS),
/* harmony export */   MONTH_IN_SECONDS: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.MONTH_IN_SECONDS),
/* harmony export */   WEEK_IN_SECONDS: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.WEEK_IN_SECONDS),
/* harmony export */   calculateChange: () => (/* binding */ calculateChange),
/* harmony export */   calculateDifferenceBetweenChartValues: () => (/* reexport safe */ _chart__WEBPACK_IMPORTED_MODULE_9__.calculateDifferenceBetweenChartValues),
/* harmony export */   convertDateStringToUNIXTimestamp: () => (/* reexport safe */ _convert_time__WEBPACK_IMPORTED_MODULE_7__.convertDateStringToUNIXTimestamp),
/* harmony export */   convertSecondsToArray: () => (/* reexport safe */ _convert_time__WEBPACK_IMPORTED_MODULE_7__.convertSecondsToArray),
/* harmony export */   createDurationFormat: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.createDurationFormat),
/* harmony export */   dateSub: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.dateSub),
/* harmony export */   decodeHTMLEntity: () => (/* binding */ decodeHTMLEntity),
/* harmony export */   expandNumFmtOptions: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.expandNumFmtOptions),
/* harmony export */   getAvailableDateRanges: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.getAvailableDateRanges),
/* harmony export */   getChartDifferenceArrow: () => (/* reexport safe */ _chart__WEBPACK_IMPORTED_MODULE_9__.getChartDifferenceArrow),
/* harmony export */   getCurrentDateRangeDayCount: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.getCurrentDateRangeDayCount),
/* harmony export */   getDateString: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.getDateString),
/* harmony export */   getFullURL: () => (/* reexport safe */ _urls__WEBPACK_IMPORTED_MODULE_10__.getFullURL),
/* harmony export */   getLocale: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.getLocale),
/* harmony export */   getPreviousDate: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.getPreviousDate),
/* harmony export */   getStorage: () => (/* reexport safe */ _storage__WEBPACK_IMPORTED_MODULE_4__.getStorage),
/* harmony export */   getURLPath: () => (/* reexport safe */ _urls__WEBPACK_IMPORTED_MODULE_10__.getURLPath),
/* harmony export */   isHashOnly: () => (/* reexport safe */ _urls__WEBPACK_IMPORTED_MODULE_10__.isHashOnly),
/* harmony export */   isNumeric: () => (/* reexport safe */ _isnumeric__WEBPACK_IMPORTED_MODULE_12__.isNumeric),
/* harmony export */   isSingleSlice: () => (/* reexport safe */ _chart__WEBPACK_IMPORTED_MODULE_9__.isSingleSlice),
/* harmony export */   isValidDateRange: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.isValidDateRange),
/* harmony export */   isValidDateString: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.isValidDateString),
/* harmony export */   isValidNumericID: () => (/* reexport safe */ _is_valid_numeric_id__WEBPACK_IMPORTED_MODULE_11__.isValidNumericID),
/* harmony export */   listFormat: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.listFormat),
/* harmony export */   markdownToHTML: () => (/* reexport safe */ _markdown__WEBPACK_IMPORTED_MODULE_6__.markdownToHTML),
/* harmony export */   normalizeURL: () => (/* reexport safe */ _urls__WEBPACK_IMPORTED_MODULE_10__.normalizeURL),
/* harmony export */   numFmt: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.numFmt),
/* harmony export */   numberFormat: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.numberFormat),
/* harmony export */   partitionReport: () => (/* reexport safe */ _partition_report__WEBPACK_IMPORTED_MODULE_14__.partitionReport),
/* harmony export */   prepareForReadableLargeNumber: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.prepareForReadableLargeNumber),
/* harmony export */   readableLargeNumber: () => (/* reexport safe */ _i18n__WEBPACK_IMPORTED_MODULE_5__.readableLargeNumber),
/* harmony export */   safelySort: () => (/* reexport safe */ _safely_sort__WEBPACK_IMPORTED_MODULE_13__.safelySort),
/* harmony export */   sanitizeHTML: () => (/* reexport safe */ _sanitize__WEBPACK_IMPORTED_MODULE_2__.sanitizeHTML),
/* harmony export */   shortenURL: () => (/* reexport safe */ _urls__WEBPACK_IMPORTED_MODULE_10__.shortenURL),
/* harmony export */   storageAvailable: () => (/* reexport safe */ _storage__WEBPACK_IMPORTED_MODULE_4__.storageAvailable),
/* harmony export */   stringToDate: () => (/* reexport safe */ _dates__WEBPACK_IMPORTED_MODULE_8__.stringToDate),
/* harmony export */   stringifyObject: () => (/* reexport safe */ _stringify__WEBPACK_IMPORTED_MODULE_3__.stringifyObject),
/* harmony export */   trackEvent: () => (/* reexport safe */ _tracking__WEBPACK_IMPORTED_MODULE_1__.trackEvent),
/* harmony export */   trackEventOnce: () => (/* reexport safe */ _tracking__WEBPACK_IMPORTED_MODULE_1__.trackEventOnce),
/* harmony export */   untrailingslashit: () => (/* reexport safe */ _sanitize__WEBPACK_IMPORTED_MODULE_2__.untrailingslashit),
/* harmony export */   validateJSON: () => (/* binding */ validateJSON)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _tracking__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tracking */ "./js/util/tracking/index.js");
/* harmony import */ var _sanitize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sanitize */ "./js/util/sanitize.js");
/* harmony import */ var _stringify__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./stringify */ "./js/util/stringify.js");
/* harmony import */ var _storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./storage */ "./js/util/storage.js");
/* harmony import */ var _i18n__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./i18n */ "./js/util/i18n.js");
/* harmony import */ var _markdown__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./markdown */ "./js/util/markdown.js");
/* harmony import */ var _convert_time__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./convert-time */ "./js/util/convert-time.js");
/* harmony import */ var _dates__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./dates */ "./js/util/dates.js");
/* harmony import */ var _chart__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chart */ "./js/util/chart.js");
/* harmony import */ var _urls__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./urls */ "./js/util/urls.js");
/* harmony import */ var _is_valid_numeric_id__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./is-valid-numeric-id */ "./js/util/is-valid-numeric-id.js");
/* harmony import */ var _isnumeric__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./isnumeric */ "./js/util/isnumeric.js");
/* harmony import */ var _safely_sort__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./safely-sort */ "./js/util/safely-sort.js");
/* harmony import */ var _partition_report__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./partition-report */ "./js/util/partition-report.js");
/**
 * Utility functions.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */
















/**
 * Calculates the change between two values.
 *
 * @since 1.24.0
 *
 * @param {number} previous The previous value.
 * @param {number} current  The current value.
 * @return {(number|null)} The percent change. Null if the input or output is invalid.
 */
function calculateChange(previous, current) {
  function isZero(value) {
    return value === '0' || value === 0;
  }

  // Prevent null result when both values are legitimately zero.
  if (isZero(previous) && isZero(current)) {
    return 0;
  }

  // Prevent divide by zero errors.
  if (isZero(previous) || Number.isNaN(previous)) {
    return null;
  }

  // Avoid NaN at all costs.
  const change = (current - previous) / previous;
  if (Number.isNaN(change) || !Number.isFinite(change)) {
    return null;
  }
  return change;
}

/**
 * Verifies whether JSON is valid.
 *
 * @since 1.0.0
 *
 * @param {string} stringToValidate The string to validate.
 * @return {boolean} Indicates JSON is valid.
 */
function validateJSON(stringToValidate) {
  try {
    return JSON.parse(stringToValidate) && !!stringToValidate;
  } catch (e) {
    return false;
  }
}

/**
 * Converts HTML text into an HTML entity.
 *
 * _.unescape doesn't seem to decode some entities for admin bar titles.
 * adding combination in this helper as a workaround.
 *
 * @since 1.0.0
 *
 * @param {string} str The string to decode.
 * @return {string} Decoded HTML entity.
 */
function decodeHTMLEntity(str) {
  if (!str) {
    return '';
  }
  const decoded = str.replace(/&#(\d+);/g, (match, dec) => {
    return String.fromCharCode(dec);
  }).replace(/(\\)/g, '');
  return (0,lodash__WEBPACK_IMPORTED_MODULE_0__.unescape)(decoded);
}

/***/ }),

/***/ "./js/util/is-valid-numeric-id.js":
/*!****************************************!*\
  !*** ./js/util/is-valid-numeric-id.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isValidNumericID: () => (/* binding */ isValidNumericID)
/* harmony export */ });
/**
 * Utility function related to checking if a given value is numeric.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Checks the given value to see if it is a positive integer.
 *
 * @since 1.11.0 Function introduced.
 * @since 1.90.0 Moved outside Tag Manager to a generic utility function.
 *
 * @param {*} input Value to check.
 * @return {boolean} Validity.
 */
function isValidNumericID(input) {
  const id = parseFloat(input) || 0;
  if (!Number.isInteger(id)) {
    return false;
  }
  return id > 0;
}

/***/ }),

/***/ "./js/util/isnumeric.js":
/*!******************************!*\
  !*** ./js/util/isnumeric.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   isNumeric: () => (/* binding */ isNumeric)
/* harmony export */ });
/**
 * Utility function related to checking if a given value is numeric.
 *
 * Site Kit by Google, Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Checks if a given value is numeric.
 *
 * @since 1.80.0
 *
 * @param {*} value The value to check.
 * @return {boolean} TRUE if a value is numeric FALSE otherwise.
 */
function isNumeric(value) {
  if (typeof value === 'number') {
    return true;
  }
  const string = (value || '').toString();
  if (!string) {
    return false;
  }
  return !isNaN(string);
}

/***/ }),

/***/ "./js/util/markdown.js":
/*!*****************************!*\
  !*** ./js/util/markdown.js ***!
  \*****************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   markdownToHTML: () => (/* binding */ markdownToHTML)
/* harmony export */ });
/**
 * Markdown utility.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Replaces markdown links with its HTML equivalents.
 *
 * @since 1.22.0
 *
 * @param {string} text Markdown text.
 * @return {string} Text with HTML links.
 */
function markdownLinks(text) {
  return text.replace(new RegExp('\\[([^\\]]+)\\]\\((https?://[^/]+\\.\\w+/?.*?)\\)', 'gi'), '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
}

/**
 * Adds paragraphs to the text.
 *
 * @since 1.22.0
 *
 * @param {string} text Markdown text.
 * @return {string} Text with HTML links.
 */
function markdownParagraphs(text) {
  return `<p>${text.replace(/\n{2,}/g, '</p><p>')}</p>`;
}

/**
 * Replaces line breaks in the text.
 *
 * @since 1.22.0
 *
 * @param {string} text Markdown text.
 * @return {string} Text with HTML links.
 */
function markdownBreaks(text) {
  return text.replace(/\n/gi, '<br>');
}

/**
 * Converts markdown to HTML.
 *
 * @since 1.22.0
 *
 * @param {string} text Markdown text.
 * @return {string} HTML version of the markdown text.
 */
function markdownToHTML(text) {
  const rules = [markdownLinks, markdownParagraphs, markdownBreaks];
  let html = text;
  for (const rule of rules) {
    html = rule(html);
  }
  return html;
}

/***/ }),

/***/ "./js/util/partition-report.js":
/*!*************************************!*\
  !*** ./js/util/partition-report.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   partitionReport: () => (/* binding */ partitionReport)
/* harmony export */ });
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! invariant */ "../node_modules/invariant/browser.js");
/* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_0__);
/**
 * Report partitioning utility.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Splits report data into segments for current and comparison ranges.
 *
 * @since 1.33.0
 * @since 1.34.0 Updated to support incomplete `report` arrays.
 *
 * @param {Array}  report               Report rows.
 * @param {Object} args                 Additional arguments.
 * @param {number} args.dateRangeLength Date range length of report segments.
 * @return {Object} Object with keys for `compareRange` and `currentRange`.
 */
function partitionReport(report, {
  dateRangeLength
}) {
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(Array.isArray(report), 'report must be an array to partition.');
  invariant__WEBPACK_IMPORTED_MODULE_0___default()(Number.isInteger(dateRangeLength) && dateRangeLength > 0, 'dateRangeLength must be a positive integer.');

  // Use a negative date range length for reverse slicing.
  const _dateRangeLength = -1 * dateRangeLength;
  return {
    // The current range should always be sliced from the end.
    currentRange: report.slice(_dateRangeLength),
    // The compare range continues from where the current left off (slicing towards the start),
    // and may be shorter (where older data is not available yet) which is fine.
    compareRange: report.slice(_dateRangeLength * 2, _dateRangeLength)
  };
}

/***/ }),

/***/ "./js/util/purify.js":
/*!***************************!*\
  !*** ./js/util/purify.js ***!
  \***************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   purify: () => (/* binding */ purify)
/* harmony export */ });
/* harmony import */ var dompurify__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dompurify */ "../node_modules/dompurify/dist/purify.js");
/* harmony import */ var dompurify__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dompurify__WEBPACK_IMPORTED_MODULE_0__);
/**
 * External dependencies
 */

const purify = dompurify__WEBPACK_IMPORTED_MODULE_0___default()(__webpack_require__.g);

/***/ }),

/***/ "./js/util/safely-sort.js":
/*!********************************!*\
  !*** ./js/util/safely-sort.js ***!
  \********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   safelySort: () => (/* binding */ safelySort)
/* harmony export */ });
/**
 * `safelySort` utility function.
 *
 * Site Kit by Google, Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Sorts an array without causing the mutation if the given parameter is an array.
 * If the parameter is not an array, it returns the parameter as is.
 *
 * @since 1.110.0
 * @since 1.128.0 Moved to the common utility directory from the key metrics directory.
 *
 * @param {Array|*} arr Param to be sorted.
 * @return {Array|*} 	Safely sorted array without mutation.
 */
function safelySort(arr) {
  return Array.isArray(arr) ? [...arr].sort() : arr;
}

/***/ }),

/***/ "./js/util/sanitize.js":
/*!*****************************!*\
  !*** ./js/util/sanitize.js ***!
  \*****************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   sanitizeHTML: () => (/* binding */ sanitizeHTML),
/* harmony export */   untrailingslashit: () => (/* binding */ untrailingslashit)
/* harmony export */ });
/* harmony import */ var _purify__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./purify */ "./js/util/purify.js");
/**
 * Internal dependencies
 */

function sanitizeHTML(unsafeHTML, domPurifyConfig = {}) {
  return {
    __html: _purify__WEBPACK_IMPORTED_MODULE_0__.purify.sanitize(unsafeHTML, domPurifyConfig)
  };
}

/**
 * Takes a string or an URL object, removes the trailing slash if any and returns it.
 *
 * @since 1.20.0
 * @private
 *
 * @param {Object|string} url A string with or without trailing slash or an URL object.
 * @return {string|undefined} The URL string after removing the trailing slash.
 */
function untrailingslashit(url) {
  const originalURL = typeof url === 'object' ? url.toString() : url;
  return originalURL?.replace?.(/\/+$/, '');
}

/***/ }),

/***/ "./js/util/storage.js":
/*!****************************!*\
  !*** ./js/util/storage.js ***!
  \****************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   getStorage: () => (/* binding */ getStorage),
/* harmony export */   storageAvailable: () => (/* binding */ storageAvailable)
/* harmony export */ });
/**
 * Storage abstraction.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Detects whether browser storage is both supported and available.
 *
 * @since 1.0.0
 *
 * @param {string} type Browser storage to test. ex localStorage or sessionStorage.
 * @return {boolean} True if the given storage is available, false otherwise.
 */
function storageAvailable(type) {
  const storage = __webpack_require__.g[type];
  if (!storage) {
    return false;
  }
  try {
    const x = '__storage_test__';
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return e instanceof DOMException && (
    // everything except Firefox
    22 === e.code ||
    // Firefox
    1014 === e.code ||
    // test name field too, because code might not be present
    // everything except Firefox
    'QuotaExceededError' === e.name ||
    // Firefox
    'NS_ERROR_DOM_QUOTA_REACHED' === e.name) &&
    // acknowledge QuotaExceededError only if there's something already stored
    0 !== storage.length;
  }
}

// Custom no-op implementation of window.Storage.
class NullStorage {
  get length() {
    return 0;
  }
  key() {
    return null;
  }
  getItem() {
    return null;
  }
  setItem() {
    // Empty method body.
  }
  removeItem() {
    // Empty method body.
  }
  clear() {
    // Empty method body.
  }
}
let storageObj;

/**
 * Gets the storage object to use.
 *
 * @since 1.0.0
 *
 * @return {Storage} Either window.sessionStorage, window.localStorage', or a
 *                   no-op implementation if neither is available.
 */
function getStorage() {
  // Only run the logic to determine the storage object once.
  if (!storageObj) {
    if (storageAvailable('sessionStorage')) {
      storageObj = __webpack_require__.g.sessionStorage;
    } else if (storageAvailable('localStorage')) {
      storageObj = __webpack_require__.g.localStorage;
    } else {
      storageObj = new NullStorage();
    }
  }
  return storageObj;
}

/***/ }),

/***/ "./js/util/stringify.js":
/*!******************************!*\
  !*** ./js/util/stringify.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   stringifyObject: () => (/* binding */ stringifyObject)
/* harmony export */ });
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! md5 */ "../node_modules/md5/md5.js");
/* harmony import */ var md5__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(md5__WEBPACK_IMPORTED_MODULE_0__);
/**
 * Stringify function.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Transforms an object into a hash string.
 *
 * This function can be used to e.g. generate cache keys, based on the given
 * object. Object properties are sorted, so even if they are provided in
 * different order, the hash will match. The function furthermore supports
 * nested objects.
 *
 * @since 1.7.0
 *
 * @param {Object} obj The object to stringify.
 * @return {string} Hash for the object.
 */
function stringifyObject(obj) {
  return md5__WEBPACK_IMPORTED_MODULE_0___default()(JSON.stringify(sortObjectProperties(obj)));
}
function sortObjectProperties(obj) {
  const orderedData = {};
  Object.keys(obj).sort().forEach(key => {
    let val = obj[key];
    if (val && 'object' === typeof val && !Array.isArray(val)) {
      val = sortObjectProperties(val);
    }
    orderedData[key] = val;
  });
  return orderedData;
}

/***/ }),

/***/ "./js/util/tracking/constants.js":
/*!***************************************!*\
  !*** ./js/util/tracking/constants.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DATA_LAYER: () => (/* binding */ DATA_LAYER),
/* harmony export */   SCRIPT_IDENTIFIER: () => (/* binding */ SCRIPT_IDENTIFIER)
/* harmony export */ });
/**
 * Constants related to event tracking.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Data layer global used for internal/private Site Kit data.
 *
 * @since 1.8.0
 * @private
 */
const DATA_LAYER = '_googlesitekitDataLayer';

/**
 * The `gtag` `<script>` identifier.
 *
 * @since 1.8.0
 * @private
 */
const SCRIPT_IDENTIFIER = 'data-googlesitekit-gtag';

/***/ }),

/***/ "./js/util/tracking/createDataLayerPush.js":
/*!*************************************************!*\
  !*** ./js/util/tracking/createDataLayerPush.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ createDataLayerPush)
/* harmony export */ });
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./js/util/tracking/constants.js");
/**
 * Internal dependencies
 */


/**
 * Returns a function which, when invoked will initialize the dataLayer and push data onto it.
 *
 * @since 1.3.0
 *
 * @param {Object} target Object to enhance with dataLayer data.
 * @return {Function} Function that pushes data onto the dataLayer.
 */
function createDataLayerPush(target) {
  /**
   * Pushes data onto the data layer.
   *
   * Must push an instance of Arguments to the target.
   * Using an ES6 spread operator (i.e. `...args`) will cause tracking events to
   * _silently_ fail.
   *
   * @since 1.0.0
   * @see {@link https://github.com/google/site-kit-wp/issues/1181}
   */
  return function dataLayerPush() {
    target[_constants__WEBPACK_IMPORTED_MODULE_0__.DATA_LAYER] = target[_constants__WEBPACK_IMPORTED_MODULE_0__.DATA_LAYER] || [];
    target[_constants__WEBPACK_IMPORTED_MODULE_0__.DATA_LAYER].push(arguments);
  };
}

/***/ }),

/***/ "./js/util/tracking/createInitializeSnippet.js":
/*!*****************************************************!*\
  !*** ./js/util/tracking/createInitializeSnippet.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ createInitializeSnippet)
/* harmony export */ });
/* harmony import */ var _createDataLayerPush__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createDataLayerPush */ "./js/util/tracking/createDataLayerPush.js");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants */ "./js/util/tracking/constants.js");
/* harmony import */ var _js_features_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/js/features/index */ "./js/features/index.js");
/**
 * Internal dependencies
 */




/**
 * Returns a function which, when invoked injects the gtag script if necessary.
 *
 * @since 1.44.0
 *
 * @param {Object} config          Tracking configuration.
 * @param {Object} dataLayerTarget Data layer parent object.
 * @return {Function} Function that injects gtag script if it isn't yet present.
 */
function createInitializeSnippet(config, dataLayerTarget) {
  const dataLayerPush = (0,_createDataLayerPush__WEBPACK_IMPORTED_MODULE_0__["default"])(dataLayerTarget);
  let hasInsertedTag;
  const {
    activeModules,
    referenceSiteURL,
    userIDHash,
    userRoles = [],
    isAuthenticated,
    pluginVersion
  } = config;

  /**
   * Injects the necessary script tag if not present.
   *
   * @since 1.118.0
   *
   * @return {boolean|Object} Tag src as scriptTagSrc property.
   */
  return function initializeSnippet() {
    const {
      document
    } = __webpack_require__.g;
    if (undefined === hasInsertedTag) {
      hasInsertedTag = !!document.querySelector(`script[${_constants__WEBPACK_IMPORTED_MODULE_1__.SCRIPT_IDENTIFIER}]`);
    }
    if (hasInsertedTag) {
      return false;
    }
    hasInsertedTag = true;

    // Sometimes the user roles returned by Site Kit/WordPress is not an
    // array, as expected, so we guard against it here.
    //
    // See: https://github.com/google/site-kit-wp/issues/8266
    const userRolesAsString = userRoles?.length ? userRoles.join(',') : '';

    // We should use the real time, and not the reference date, when
    // measuring when we initialized tracking.
    dataLayerPush('js', new Date()); // eslint-disable-line sitekit/no-direct-date
    dataLayerPush('config', config.trackingID, {
      groups: 'site_kit',
      send_page_view: config.isSiteKitScreen,
      domain: referenceSiteURL,
      plugin_version: pluginVersion || '',
      enabled_features: Array.from(_js_features_index__WEBPACK_IMPORTED_MODULE_2__.enabledFeatures).join(','),
      active_modules: activeModules.join(','),
      authenticated: isAuthenticated ? '1' : '0',
      user_properties: {
        user_roles: userRolesAsString,
        user_identifier: userIDHash
      }
    });

    // If not present, inject it and initialize dataLayer.
    const scriptTag = document.createElement('script');
    scriptTag.setAttribute(_constants__WEBPACK_IMPORTED_MODULE_1__.SCRIPT_IDENTIFIER, '');
    scriptTag.async = true;
    scriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${config.trackingID}&l=${_constants__WEBPACK_IMPORTED_MODULE_1__.DATA_LAYER}`;
    document.head.appendChild(scriptTag);
    return {
      scriptTagSrc: `https://www.googletagmanager.com/gtag/js?id=${config.trackingID}&l=${_constants__WEBPACK_IMPORTED_MODULE_1__.DATA_LAYER}`
    };
  };
}

/***/ }),

/***/ "./js/util/tracking/createTrackEvent.js":
/*!**********************************************!*\
  !*** ./js/util/tracking/createTrackEvent.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ createTrackEvent)
/* harmony export */ });
/* harmony import */ var _createDataLayerPush__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createDataLayerPush */ "./js/util/tracking/createDataLayerPush.js");
/**
 * Internal dependencies
 */


/**
 * Returns a function which, when invoked tracks a single event.
 *
 * @since 1.3.0
 *
 * @param {Object}   config            Tracking configuration.
 * @param {Object}   dataLayerTarget   Data layer parent object.
 * @param {Function} initializeSnippet Function to initialize tracking.
 * @param {Object}   _global           The global window object.
 * @return {Function} Function that tracks an event.
 */
function createTrackEvent(config, dataLayerTarget, initializeSnippet, _global) {
  const dataLayerPush = (0,_createDataLayerPush__WEBPACK_IMPORTED_MODULE_0__["default"])(dataLayerTarget);

  /**
   * Send an Analytics tracking event.
   *
   * @since 1.3.0
   *
   * @param {string} category The category of the event.
   * @param {string} action   The action name of the event.
   * @param {string} [label]  Optional. The label of the event.
   * @param {number} [value]  Optional. A non-negative integer that will appear as the event value.
   * @return {Promise} Promise that always resolves.
   */
  // eslint-disable-next-line require-await
  return async function trackEvent(category, action, label, value) {
    const {
      trackingEnabled
    } = config;
    if (!trackingEnabled) {
      // Resolve immediately if tracking is disabled.
      return null;
    }
    initializeSnippet();
    const eventData = {
      send_to: 'site_kit',
      event_category: category,
      event_label: label,
      value
    };
    return new Promise(resolve => {
      // This timeout ensures a tracking event does not block the user
      // event if it is not sent (in time).
      // If the event beacon fails, it shouldn't reject the promise since event
      // tracking should not result in user-facing errors. It will just
      // trigger a console warning.
      function failCallback() {
        _global.console.warn(`Tracking event "${action}" (category "${category}") took too long to fire.`);
        resolve();
      }
      const failTimeout = setTimeout(failCallback, 1000);
      // eslint-disable-next-line camelcase
      function event_callback() {
        clearTimeout(failTimeout);
        resolve();
      }
      dataLayerPush('event', action, {
        ...eventData,
        event_callback
      });

      // If the client-side opt-out is present, the event_callback will never be called
      // so we call it here to prevent the warning and added delay.
      if (_global._gaUserPrefs?.ioo?.()) {
        event_callback();
      }
    });
  };
}

/***/ }),

/***/ "./js/util/tracking/createTracking.js":
/*!********************************************!*\
  !*** ./js/util/tracking/createTracking.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ createTracking)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "../node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _createInitializeSnippet__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./createInitializeSnippet */ "./js/util/tracking/createInitializeSnippet.js");
/* harmony import */ var _createTrackEvent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./createTrackEvent */ "./js/util/tracking/createTrackEvent.js");
/**
 * Site Kit by Google, Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */


/**
 * Internal dependencies
 */


const DEFAULT_CONFIG = {
  activeModules: [],
  isAuthenticated: false,
  referenceSiteURL: '',
  trackingEnabled: false,
  trackingID: '',
  userIDHash: '',
  userRoles: []
};

/**
 * Initializes tracking.
 *
 * @since 1.3.0
 *
 * @param {Object} newConfig       New configuration.
 * @param {Object} dataLayerTarget Data layer parent object.
 * @param {Object} _global         The global window object.
 * @return {Object} Tracking config.
 */
function createTracking(newConfig, dataLayerTarget = __webpack_require__.g, _global = __webpack_require__.g) {
  const config = {
    ...DEFAULT_CONFIG,
    ...newConfig
  };
  // Remove any trailing slash from the reference URL.
  if (config.referenceSiteURL) {
    config.referenceSiteURL = config.referenceSiteURL.toString().replace(/\/+$/, '');
  }
  const initializeSnippet = (0,_createInitializeSnippet__WEBPACK_IMPORTED_MODULE_1__["default"])(config, dataLayerTarget);
  const trackEvent = (0,_createTrackEvent__WEBPACK_IMPORTED_MODULE_2__["default"])(config, dataLayerTarget, initializeSnippet, _global);
  const onceTrackedEventsMap = {};
  function trackEventOnce(...params) {
    const key = JSON.stringify(params);
    if (!onceTrackedEventsMap[key]) {
      onceTrackedEventsMap[key] = (0,lodash__WEBPACK_IMPORTED_MODULE_0__.once)(trackEvent);
    }
    onceTrackedEventsMap[key](...params);
  }
  return {
    enableTracking: function enableTracking() {
      config.trackingEnabled = true;
    },
    disableTracking: function disableTracking() {
      config.trackingEnabled = false;
    },
    initializeSnippet,
    isTrackingEnabled: function isTrackingEnabled() {
      return !!config.trackingEnabled;
    },
    trackEvent,
    trackEventOnce
  };
}

/***/ }),

/***/ "./js/util/tracking/index.js":
/*!***********************************!*\
  !*** ./js/util/tracking/index.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   disableTracking: () => (/* binding */ disableTracking),
/* harmony export */   enableTracking: () => (/* binding */ enableTracking),
/* harmony export */   isTrackingEnabled: () => (/* binding */ isTrackingEnabled),
/* harmony export */   toggleTracking: () => (/* binding */ toggleTracking),
/* harmony export */   trackEvent: () => (/* binding */ trackEvent),
/* harmony export */   trackEventOnce: () => (/* binding */ trackEventOnce)
/* harmony export */ });
/* harmony import */ var _createTracking__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createTracking */ "./js/util/tracking/createTracking.js");
/**
 * Event tracking utilities.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* eslint-disable sitekit/jsdoc-no-unnamed-boolean-params */

/**
 * Internal dependencies
 */

const {
  activeModules = [],
  isSiteKitScreen,
  trackingEnabled,
  trackingID,
  referenceSiteURL,
  userIDHash,
  isAuthenticated,
  userRoles
} = __webpack_require__.g._googlesitekitTrackingData || {};

// Access the plugin version directly without destructuring as Webpack's DefinePlugin
// performs text replacement at build time and doesn't support destructuring patterns.
// See: https://github.com/google/site-kit-wp/issues/11802#issuecomment-3562955579
const pluginVersion = "1.168.0";
const initialConfig = {
  activeModules,
  trackingEnabled,
  trackingID,
  referenceSiteURL,
  userIDHash,
  isSiteKitScreen,
  userRoles,
  isAuthenticated,
  pluginVersion
};
const {
  enableTracking,
  disableTracking,
  isTrackingEnabled,
  initializeSnippet,
  trackEvent,
  trackEventOnce
} = (0,_createTracking__WEBPACK_IMPORTED_MODULE_0__["default"])(initialConfig);

/**
 * Changes the active state of tracking.
 *
 * @since 1.3.0
 *
 * @param {boolean} activeStatus The new state to set.
 */
function toggleTracking(activeStatus) {
  if (!!activeStatus) {
    enableTracking();
  } else {
    disableTracking();
  }
}

// Bootstrap on import if tracking is allowed.
if (isSiteKitScreen && trackingEnabled) {
  initializeSnippet();
}


/***/ }),

/***/ "./js/util/urls.js":
/*!*************************!*\
  !*** ./js/util/urls.js ***!
  \*************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   getFullURL: () => (/* binding */ getFullURL),
/* harmony export */   getURLPath: () => (/* binding */ getURLPath),
/* harmony export */   isHashOnly: () => (/* binding */ isHashOnly),
/* harmony export */   normalizeURL: () => (/* binding */ normalizeURL),
/* harmony export */   shortenURL: () => (/* binding */ shortenURL)
/* harmony export */ });
/* harmony import */ var _wordpress_url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @wordpress/url */ "../node_modules/@wordpress/url/build-module/is-url.js");
/**
 * URL pathname getter utility function.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */


/**
 * Returns the path from a URL, omitting its protocol, hostname, query params, and hash.
 *
 * @since 1.24.0
 *
 * @param {string} url The URL to get the path from.
 * @return {string} The URL path.
 */
function getURLPath(url) {
  try {
    return new URL(url).pathname;
  } catch {}
  return null;
}

/**
 * Returns the absolute URL from a path including the siteURL.
 *
 * @since 1.32.0
 *
 * @param {string} siteURL The siteURL fo the WordPress install.
 * @param {string} path    The path.
 * @return {string} The URL path.
 */
function getFullURL(siteURL, path) {
  try {
    return new URL(path, siteURL).href;
  } catch {}
  return (typeof siteURL === 'string' ? siteURL : '') + (typeof path === 'string' ? path : '');
}

/**
 * Normalizes URL by removing protocol, www subdomain and trailing slash.
 *
 * @since 1.33.0
 *
 * @param {string} incomingURL The original URL.
 * @return {string} Normalized URL.
 */
function normalizeURL(incomingURL) {
  if (typeof incomingURL !== 'string') {
    return incomingURL;
  }
  return incomingURL
  // Remove protocol and optional "www." prefix from the URL.
  .replace(/^https?:\/\/(www\.)?/i, '')
  // Remove trailing slash.
  .replace(/\/$/, '');
}

/**
 * Checks if a string is not a full URL and simply a hash / anchor link.
 *
 * @since 1.49.0
 *
 * @param {string} url The URL or Hash string to test.
 * @return {boolean} Returns true if the string is only a hash and not a full URL.
 */
function isHashOnly(url) {
  return /^#\w[A-Za-z0-9-_]*$/.test(url);
}

/**
 * Shortens a URL to fit a given length.
 *
 * @since 1.49.0
 *
 * @param {string} url      The original URL to shorten.
 * @param {number} maxChars The maximum length of the URL.
 * @return {string} The shortened URL.
 */
function shortenURL(url, maxChars) {
  if (!(0,_wordpress_url__WEBPACK_IMPORTED_MODULE_0__.isURL)(url)) {
    return url;
  }
  if (url.length <= maxChars) {
    return url;
  }
  const urlObject = new URL(url);
  const shortenedURL = url.replace(urlObject.origin, '');
  if (shortenedURL.length < maxChars) {
    return shortenedURL;
  }
  const extraChars = shortenedURL.length - Math.floor(maxChars) + 1; // 1 is the length of "…".
  return '…' + shortenedURL.substr(extraChars);
}

/***/ }),

/***/ "@wordpress/i18n":
/*!*****************************************!*\
  !*** external ["googlesitekit","i18n"] ***!
  \*****************************************/
/***/ ((module) => {

module.exports = googlesitekit.i18n;

/***/ }),

/***/ "googlesitekit-api":
/*!****************************************!*\
  !*** external ["googlesitekit","api"] ***!
  \****************************************/
/***/ ((module) => {

module.exports = googlesitekit.api;

/***/ }),

/***/ "googlesitekit-data":
/*!*****************************************!*\
  !*** external ["googlesitekit","data"] ***!
  \*****************************************/
/***/ ((module) => {

module.exports = googlesitekit.data;

/***/ })

},
/******/ __webpack_require__ => { // webpackRuntimeModules
/******/ var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
/******/ __webpack_require__.O(0, ["googlesitekit-vendor"], () => (__webpack_exec__("./js/googlesitekit-datastore-user.js")));
/******/ var __webpack_exports__ = __webpack_require__.O();
/******/ }
]);
//# sourceMappingURL=googlesitekit-datastore-user.js.map