import { reflect as reflect$1, string as string$1, cookies, eventFields, delegatesInfo, keyValue, network } from '@amp-metrics/mt-metricskit-utils-private';
import Constraints, { connectConstraintConfig } from '@amp-metrics/mt-client-constraints';
import { system, eventHandlers } from '@amp-metrics/ae-client-kit-core';
import { loggerNamed } from '@amp-metrics/mt-client-logger-core';

var info = { version: '8.6.3', name: 'mt-metricskit-processor-clickstream' };

/*
 *  src/metrics/utils/delegate_extension.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2016 Apple Inc. All rights reserved.
 *
 */
/*
 * Delegate info functions to be used by _utils.reflect.attachDelegate
 */
var delegateInfo = {
    /**
     * Returns the name of this repository
     * Used by _utils.reflect.attachDelegate to create
     * a delegate dependence tree for the optional
     * base field, xpDelegatesInfo
     * @returns {String} Name of this repository
     */
    mtName: function () {
        return info.name;
    },
    /**
     * Returns version of this repo
     * Used by _utils.reflect.attachDelegate to create
     * a delegate dependence tree for the optional
     * base field, xpDelegatesInfo
     * @returns {String} Version of this repo
     */
    mtVersion: function () {
        return info.version;
    }
};

/**
 * Delegate-related functions (intended to eventually contain
 * all needed functions to be delegateable, like 'setDelegate')
 * @constructor
 */
var delegateExtension = {
    /**
     * Adds delegate info methods to the target (delegateable) object
     * @param {Object} targetObj Delegateable object to attach info methods to
     */
    attachDelegateInfo: function (targetObj) {
        reflect$1.extend(targetObj, delegateInfo);
    }
};

/*
 *  src/merics/config.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2016 Apple Inc. All rights reserved.
 *
 */

/**
 * Extend the metrics config instance with convenience functions and delegate info
 * This should be done for every config instance that MetricsKit uses:
 * once for the default config, and once for the topic-specific config if metrics.init() is used
 * @param {Config} configInstance
 */
function initializeConfig(configInstance) {
    connectConstraintConfig(configInstance);
    delegateExtension.attachDelegateInfo(configInstance);
}

function cleanupConfig(topicConfig) {
    topicConfig.cleanup();
}

/*
 *  src/metrics/utils/constants.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2019 Apple Inc. All rights reserved.
 *
 */

var BASE_FIELDS$1 = [
    'constraintProfile',
    'constraintProfiles',
    'clientId',
    'isSignedIn',
    'page',
    'pageContext',
    'pageDetails',
    'pageId',
    'pageType',
    'xpVersionMetricsKit',
    'xpDelegatesInfo'
];

var ENVIRONMENT_REQUIRED_FIELDS = [
    'capacityData',
    'capacityDataAvailable',
    'capacityDisk',
    'capacitySystem',
    'capacitySystemAvailable',
    'dsId',
    'hostApp',
    'pageUrl',
    'pixelRatio',
    'userType',
    'windowInnerHeight',
    'windowInnerWidth',
    'windowOuterHeight',
    'windowOuterWidth'
];

var ENVIRONMENT_OPTIONAL_FIELDS = [
    'browser',
    'consumerId',
    'consumerNs',
    'hostAppVersion',
    'parentPageUrl',
    'userId',
    'xpUserIdSyncState',
    'xpAccountsMatch'
];

// These constants are used internally but not exposed publicly
var constants = {
    METRICS_KIT_BASE_FIELDS: BASE_FIELDS$1.concat(ENVIRONMENT_REQUIRED_FIELDS, ENVIRONMENT_OPTIONAL_FIELDS),
    // Used to remove the fields which are not base field in MetricsKit
    IGNORED_BASE_FIELDS: [
        'osLanguages' // only available in "enter" event handler
    ],
    REQUIRED_ENVIRONMENT_FIELD_NAMES: ENVIRONMENT_REQUIRED_FIELDS.concat('connectionType'),
    OPTIONAL_ENVIRONMENT_FIELD_NAMES: ENVIRONMENT_OPTIONAL_FIELDS.concat(['clientId', 'cookie', 'osLanguages']) // This is an optional field in MetricsKit, but a required field in client-kit-core
};

/*
 *  src/metrics/system/environment.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var Environment = system.Environment;
var exceptionString$1 = string$1.exceptionString;
var REQUIRED_ENVIRONMENT_FIELD_NAMES = constants.REQUIRED_ENVIRONMENT_FIELD_NAMES;
var OPTIONAL_ENVIRONMENT_FIELD_NAMES = constants.OPTIONAL_ENVIRONMENT_FIELD_NAMES;
var _prototypeInitialized = false;
var noOp = function () {};

/**
 * Provides a set of environment-specific (platform-specific) functions which can be individually overridden for the needs
 * of the particular environment, or replaced en masse by providing a single replacement environment delegate object
 * The functionality in this class is typically replaced via a delegate.
 * DEFAULT implementation: console logging
 * @see setDelegate
 * @delegatable
 * @constructor
 */
var MetricsKitEnvironment = function MetricsKitEnvironment() {
    Environment.apply(this, arguments);
    if (!_prototypeInitialized) {
        _prototypeInitialized = true;
        REQUIRED_ENVIRONMENT_FIELD_NAMES.forEach(function (fieldName) {
            MetricsKitEnvironment.prototype[fieldName] = function () {
                throw exceptionString$1('metrics.system.environment', fieldName);
            };
        });

        OPTIONAL_ENVIRONMENT_FIELD_NAMES.forEach(function (fieldName) {
            MetricsKitEnvironment.prototype[fieldName] = noOp;
        });
    }
};

MetricsKitEnvironment.prototype = new Environment();
MetricsKitEnvironment.prototype.constructor = MetricsKitEnvironment;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
MetricsKitEnvironment.prototype.setDelegate = function setDelegate(delegate) {
    // This is a bit of a cheat, but it allows us to not force our users to have a whole delegate just for cookies...
    // we let them merge it in with their environment delegate:
    cookies.setDelegate(delegate);
    return reflect$1.attachDelegate(this, delegate);
};

/*
 *  src/metrics/system/event_recorder.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Provides a replaceable "recordEvent" function to enqueue events to be sent to the metrics server.
 * The functionality in this class is typically replaced via a delegate.
 * DEFAULT implementation: error logged via logger.
 * @see setDelegate
 * @delegatable
 * @constructor
 */
var EventRecorder = function EventRecorder() {};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
EventRecorder.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Enqueues a JSON an event as JSON
 * NO DEFAULT IMPLEMENTATION... THIS METHOD MUST BE REPLACED
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @param {Promise|Object} eventFields a Promise/JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule.
 * @returns {Object} the recorded event, or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the blacklistedEvents, etc.)
 * @overridable
 */
EventRecorder.prototype.recordEvent = function recordEvent(topic, eventFields) {
    // Don't wrap this in a helper function or the backtrace won't be as nice.
    throw string$1.exceptionString('metrics.system.event_recorder', 'recordEvent');
};

/**
 * The methodology being used to send batches of events to the server
 * This field should be hardcoded in the client based on what method it is using to encode and send its events to Figaro.
 * The three typical values are:
 *      "itms" - use this value when/if JavaScript code enqueues events for sending via the "itms.recordEvent()" method in ITML.
 *      "itunes" - use this value when/if JavaScript code enqueues events by calling the "iTunes.recordEvent()" method in Desktop Store apps.
 *      "javascript" - use this value when/if JavaScript code enqueues events for sending via the JavaScript eventQueue management. This is typically only used by older clients which don't have the built-in functionality of itms or iTunes available to them.
 * NO DEFAULT IMPLEMENTATION... THIS METHOD MUST BE REPLACED
 * @example "itms", "itunes", "javascript"
 * @returns {String}
 * @overridable
 */
EventRecorder.prototype.sendMethod = function sendMethod() {
    // Don't wrap this in a helper function or the backtrace won't be as nice.
    throw string$1.exceptionString('metrics.system.event_recorder', 'sendMethod');
};

/**
 * Sends any remaining events in the queue, then clears it
 * NO DEFAULT IMPLEMENTATION... THIS METHOD SHOULD BE REPLACED IF THE DELEGATE ENVIRONMENT SUPPORTS IT
 * @param {Boolean} appIsExiting - if events are being flushed due to your app exiting (or page going away for web-apps), pass "true".
 *                  This allows MetricsKit to modify its flush strategy to attempt to post events prior to actual termination.
 *                  In cases where appIsExiting==false, the parameter may be omitted.
 */
EventRecorder.prototype.flushUnreportedEvents = function flushUnreportedEvents(appIsExiting) {};

/*
 *  src/metrics/system/logger.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */
var logger = loggerNamed('mt-metricskit-processor-clickstream');

/*
 *  src/metrics/system/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var System = function System() {
    this.environment = new MetricsKitEnvironment();
    this.eventRecorder = new EventRecorder();
    this.logger = logger;

    for (var key in this) {
        delegateExtension.attachDelegateInfo(this[key]);
    }
};

/*
 *  src/utils/metrics_data.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2020 Apple Inc. All rights reserved.
 *
 */

/**
 *
 * @param props
 * @param props.processor
 * @param props.eventMetricsDataPromise
 * @constructor
 */
var MetricsData = function MetricsData(props) {
    // @private
    this._processor = props.processor;
    // @private
    this._eventMetricsDataPromise = props.eventMetricsDataPromise;
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
MetricsData.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

MetricsData.prototype.toJSON = function toJSON() {
    return this._eventMetricsDataPromise.catch(
        function (err) {
            this._processor.system.logger.error('An error occurred when generating Metrics Data. Error: \n' + err);
            return null; // return null to ignore the event
        }.bind(this)
    );
};

/**
 * Enqueues the event data to the topic queue
 * @param {String} topic defines the Figaro "topic" that this event should be stored under
 * @returns {Promise} a Promise that includes the recorded event or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the blacklistedEvents, etc.)
 */
MetricsData.prototype.recordEvent = function recordEvent(topic) {
    var vargs = Array.prototype.slice.call(arguments, 1);
    return this._processor.system.eventRecorder.recordEvent.apply(
        this._processor.system.eventRecorder,
        [topic, this.toJSON()].concat(vargs)
    );
};

/*
 *  src/metrics/event_handlers/click_stream_event_handler.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var exceptionString = string$1.exceptionString;
var ClickStreamEventHandler = function ClickStreamEventHandler(clickstreamProcessor) {
    // @private
    this._processor = clickstreamProcessor;
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple PerfKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @return {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
ClickStreamEventHandler.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 * @overridable
 * NOTE: this method must be overridden by the sub class
 */
ClickStreamEventHandler.prototype.knownFields = function knownFields() {
    throw exceptionString('ClickStreamEventHandler', 'knownFields');
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 * NOTE: this method must be overridden by the sub class
 */
ClickStreamEventHandler.prototype.eventType = function (callerSuppliedEventFields) {
    throw exceptionString('ClickStreamEventHandler', 'eventType');
};

/**
 * All of the various eventHandlers invoke this method to generate their metrics data
 * The data is a simple map object (dictionary) with all the fields required by Figaro for that event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * This function expects to be called with the correct context (eg base.processMetricsData.apply(this, arguments))
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * This method will check for any disabled/blacklisted events or fields, add base fields, and process/merge all data
 * @returns {Object} key/value pairs of all "page" fields + "base" fields required by Figaro
 * WARNING: May return "null" if metrics and/or the specific eventType for this handler is disabled, or on error.
 */
ClickStreamEventHandler.prototype.processMetricsData = function processMetricsData(
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs) */
) {
    var callArguments = arguments;
    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(callArguments, 3);
    var eventType = this.eventType(callerSuppliedEventFieldsMapsArray);
    var config = this._processor.config;
    var constraints = this._processor._constraints;
    var logger = this._processor.system.logger;

    var eventMetricsDataPromise = config
        .metricsDisabledOrBlacklistedEvent(eventType)
        .then(function (disabled) {
            if (disabled) {
                throw 'event was disabled';
            }
        })
        .then(
            function () {
                var includeBaseFields =
                    typeof this.mtIncludeBaseFields == 'function' ? this.mtIncludeBaseFields() : true;
                var baseEventFields = null;
                if (includeBaseFields) {
                    // Get the base fields from the base event handler
                    var baseEventHandler = this._processor.eventHandlers.base;
                    baseEventFields = baseEventHandler.metricsData.apply(baseEventHandler, callArguments);
                } else {
                    baseEventFields = {};
                }

                return baseEventFields;
            }.bind(this)
        )
        .then(
            function (baseMetricsFields) {
                var valueHandlerTasks = [];
                callerSuppliedEventFieldsMapsArray = [baseMetricsFields].concat(callerSuppliedEventFieldsMapsArray);
                var eventFieldPromises = eventFields.processMetricsData(
                    this,
                    this.knownFields(),
                    true,
                    callerSuppliedEventFieldsMapsArray
                );
                var metricsData = {};
                Object.keys(eventFieldPromises).forEach(function (field) {
                    var fieldValue = eventFieldPromises[field];
                    var valueHandler = Promise.resolve(fieldValue).then(function (value) {
                        metricsData[field] = value;
                    });
                    valueHandlerTasks.push(valueHandler);
                });

                return Promise.all(valueHandlerTasks).then(function () {
                    return metricsData;
                });
            }.bind(this)
        )
        .then(function (eventFields) {
            return constraints.applyConstraintTreatments(eventFields);
        })
        .then(function (eventFields) {
            return config.removeBlacklistedFields(eventFields);
        })
        .then(function (eventFields) {
            return config.applyDeRes(eventFields);
        })
        .catch(
            function (e) {
                logger.error(
                    'MetricsKit: Unable to generate the event (' +
                        this.eventType(callerSuppliedEventFieldsMapsArray) +
                        ') for the topic ' +
                        this._processor.config.topic() +
                        ', due to ' +
                        e
                );
                return null;
            }.bind(this)
        );

    return new MetricsData({
        processor: this._processor,
        eventMetricsDataPromise: eventMetricsDataPromise
    });
};

/*
 *  src/metrics/event_handlers/account.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Account = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Account.prototype = Object.create(ClickStreamEventHandler.prototype);
Account.prototype.constructor = Account;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Account.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed account, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Account.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Account.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Account.prototype.eventType = function (callerSuppliedEventFields) {
    return 'account';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Account.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/base.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var BASE_FIELDS = constants.METRICS_KIT_BASE_FIELDS;
var IGNORED_BASE_FIELDS = constants.IGNORED_BASE_FIELDS;
var Base$1 = eventHandlers.Base;

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "base" fields common to all metrics events.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var ClickstreamProcessorBase = function (clickstreamProcessor) {
    Base$1.apply(this, arguments);
};

ClickstreamProcessorBase.prototype = Object.create(Base$1.prototype);
ClickstreamProcessorBase.prototype.constructor = ClickstreamProcessorBase;

/**
 * The active environment class
 * @see src/metrics/system/Environment
 * @return {Environment}
 */
ClickstreamProcessorBase.prototype.environment = function environment() {
    return this._processor.system.environment;
};

/**
 * The active eventRecorder
 * @see src/metrics/system/eventRecorder
 * @return {Object} an eventRecorder
 */
ClickstreamProcessorBase.prototype.eventRecorder = function eventRecorder() {
    return this._processor.system.eventRecorder;
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
ClickstreamProcessorBase.prototype.knownFields = function knownFields() {
    var parentKnownFields = Base$1.prototype.knownFields.call(this);
    if (IGNORED_BASE_FIELDS && IGNORED_BASE_FIELDS.length > 0) {
        parentKnownFields = parentKnownFields.slice();
        IGNORED_BASE_FIELDS.forEach(function (ignoredField) {
            var ignoredFieldIndex = parentKnownFields.indexOf(ignoredField);
            if (ignoredFieldIndex > -1) {
                parentKnownFields.splice(ignoredFieldIndex, 1);
            }
        });
    }

    return parentKnownFields.concat(BASE_FIELDS);
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary) with all the "base" fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each *known* field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.base.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {Promise} A Promise that with key/value pairs of all "page" fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
ClickstreamProcessorBase.prototype.metricsData = function metricsData(
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var metricsData = {};
    var valueTasks = [];
    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(arguments, 3);
    var utils = this._processor.utils;

    return this._processor.config
        .value('metricsBase')
        .then(
            function (configBaseFields) {
                if (configBaseFields) {
                    callerSuppliedEventFieldsMapsArray.push(configBaseFields);
                }
                var eventFieldPromises = utils.eventFields.processMetricsData(
                    this,
                    this.knownFields(),
                    pageId,
                    pageType,
                    pageContext,
                    callerSuppliedEventFieldsMapsArray
                );
                Object.keys(eventFieldPromises).forEach(function (field) {
                    var fieldValue = eventFieldPromises[field];
                    var valueHandler = Promise.resolve(fieldValue).then(function (value) {
                        metricsData[field] = value;
                    });
                    valueTasks.push(valueHandler);
                });

                return valueTasks;
            }.bind(this)
        )
        .then(function (valueTasks) {
            return Promise.all(valueTasks).then(function () {
                return metricsData;
            });
        });
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate()))
 */

// Generate the metricskit specified base field accessors
// NOTE: dynamically generate environment based accessors before the customized accessors to make these accessors to be overridable by the customized accessors.
BASE_FIELDS.forEach(function (fieldName) {
    ClickstreamProcessorBase.prototype[fieldName] = function (callerSuppliedEventFields) {
        var environment = this._processor.system.environment;
        return (callerSuppliedEventFields && callerSuppliedEventFields[fieldName]) || environment[fieldName]();
    };
});

/**
 * The name of the constraint profile used to apply constraints to fields within an event.
 * @example "strict"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|string}
 * @overridable
 */
ClickstreamProcessorBase.prototype.constraintProfile = function constraintProfile(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (callerSuppliedEventFields && callerSuppliedEventFields.constraintProfile) || config.constraintProfile();
};

/**
 * The names of the constraint profiles used to apply constraints to fields within an event.
 * NOTE: This method returns the constraint profiles that are used for Constraints v2 syntax. The constraintProfile() returns the profile that is used for Constraints v1 syntax
 * @example "[strict]"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|string}
 * @overridable
 */
ClickstreamProcessorBase.prototype.constraintProfiles = function constraintProfiles(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (callerSuppliedEventFields && callerSuppliedEventFields.constraintProfiles) || config.constraintProfiles();
};

/**
 * A unique identifier for each event
 * @returns {String}
 * @overridable
 */
ClickstreamProcessorBase.prototype.clientEventId = function clientEventId(callerSuppliedEventFields) {
    var eventId = callerSuppliedEventFields && callerSuppliedEventFields.clientEventId;
    if (!eventId) {
        if (string$1.cryptoRandomBase62String) {
            eventId = string$1.cryptoRandomBase62String(true);
        }
        if (!eventId) {
            eventId = string$1.uuid();
        }
    }
    return eventId;
};

/**
 * Return the value of the "xp_ci" cookie
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|String} the value of the "xp_ci" cookie
 * @overridable
 */
ClickstreamProcessorBase.prototype.clientId = function clientId(callerSuppliedEventFields) {
    var clientId;
    var config = this._processor.config;

    if (callerSuppliedEventFields && callerSuppliedEventFields.clientId) {
        clientId = callerSuppliedEventFields.clientId;
    } else if (this._processor.system.environment.clientId()) {
        clientId = this._processor.system.environment.clientId();
    } else {
        clientId = config.value('ignoreClientIdCookie').then(function (ignoreClientIdCookie) {
            if (!ignoreClientIdCookie) {
                return cookies.get('xp_ci');
            }
            return undefined;
        });
    }

    return clientId;
};

/**
 * Whether or not the user is signed in
 * @example true, false
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {boolean} true if the user is signed in (app has access to dsid), false if not
 * @overridable
 */
ClickstreamProcessorBase.prototype.isSignedIn = function isSignedIn(callerSuppliedEventFields) {
    return callerSuppliedEventFields && 'isSignedIn' in callerSuppliedEventFields
        ? callerSuppliedEventFields.isSignedIn
        : !!this.dsId(callerSuppliedEventFields);
};

/**
 * A unique descriptor for the page.
 * Usually [pageType_pageId]
 * If no pageId exists, "page" may be a textual identifier (e.g. "NewStation_Genres", "LearnMore_HD").
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * @example Genre_168577
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|String} a unique descriptor for the page
 * @overridable
 */
ClickstreamProcessorBase.prototype.page = function page(callerSuppliedEventFields) {
    if (callerSuppliedEventFields) {
        if (callerSuppliedEventFields.page) {
            return callerSuppliedEventFields.page;
        } else if (this.pageType(callerSuppliedEventFields) && this.pageId(callerSuppliedEventFields)) {
            var config = this._processor.config;
            var pageType = this.pageType(callerSuppliedEventFields);
            var pageId = this.pageId(callerSuppliedEventFields);

            return config.value('compoundSeparator').then(function (separator) {
                return pageType + separator + pageId;
            });
        }
    } else {
        throw 'No data provided to event_handlers/base page function';
    }
};

/**
 * The context within which a page is viewed.  Contexts usually provide independent streams of activity.
 * Many implementations return the tab that a user is currently on.
 * @example
 * iTunes Desktop: "InTheStore" or "Main"
 * iOS iTunes apps: tab name (e.g. "Featured", "TopCharts", etc)
 * iOS Store sheets:  "Sheet" (e.g. AppStore page launched as a sheet within Mail, Springboard’s "Near Me", Maps’ "Nearby Apps")
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} the context within which a page is viewed.  Contexts usually provide independent streams of activity
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageContext = function pageContext(callerSuppliedEventFields) {
    return callerSuppliedEventFields && callerSuppliedEventFields.pageContext;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * User-readable details describing page.
 * May contain localized values (e.g. "Alicia Keys-Girl On Fire", "MusicMain").
 * Max length 25 characters.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client, if needed.
 * @example "Top Paid iPhone Apps_Mobile Software Applications"
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} user-readable details describing page
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageDetails = function pageDetails(callerSuppliedEventFields) {
    return callerSuppliedEventFields && callerSuppliedEventFields.pageDetails;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * String ID of the page’s content.
 * Used to concatenate with the "pageType" param using the "compoundSeparator" config value (typically "_") to produce "page" values of the form: pageType_pageId
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally the identifier in some persistent store.
 * Search Results pages may have a pageId which refers to their specific dataSet, otherwise known as dataSetId.
 * If the page is better identified by a descriptive string rather than a content ID, this field may be hard-coded, but it should be unique within the set of pages displayable by the app
 * the descriptive string may appear in the "page" field instead.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * @example 168577, 1, "Welcome", etc.
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} string ID of the page’s content
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageId = function pageId(callerSuppliedEventFields) {
    // TODO:KBERN: add screamer here if this is not provided?
    return callerSuppliedEventFields && callerSuppliedEventFields.pageId;
};

/**
 * IMPORTANT: This field cannot be deduced by this class, so either:
 *              a. this method needs to be overridden by the caller,
 *              b. the caller should pass this in as part of the key/value in the "callerSuppliedEventFieldsMapN(varargs)" parameter on the metricsData() call
 * Name for the group of pages this page is (e.g. "Album" or "Grouping").
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app),
 * then this field would be generated by the client.
 * Used to concatenate with the "pageId" param using the "compoundSeparator" config value (typically "_") to produce "page" values of the form: pageType_pageId
 * @example "Genre", "Album", "Grouping", "Picker", "Recommendations", "Feed", "Search", "Subscribe", etc.)
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {String} name for the group of pages this page is (e.g. "Album" or "Grouping").
 * @overridable
 */
ClickstreamProcessorBase.prototype.pageType = function pageType(callerSuppliedEventFields) {
    // TODO:KBERN: add screamer here if this is not provided?
    return callerSuppliedEventFields && callerSuppliedEventFields.pageType;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * This is valuable for problem analysis because it indicates if and how clients are honoring the "viewablePercentage" value
 * they were supplied with.
 * This cannot be a "passthrough" field, because it can change (via new config) during program execution, so the value
 * in effect at event creation time is what is needed.
 * @example 0.5
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Promise|number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
ClickstreamProcessorBase.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.xpViewablePercentage) ||
        config.value('impressions.viewablePercentage')
    );
};

/**
 * The version of MetricsKit being used
 * Pulled from the version in the package.json via
 * the dynamically created info.js
 * @example "0.1.3", "2.0.1"
 * @returns {String} version of MetricsKit being used
 * @overridable //this should be changed to not be overridable
 */
ClickstreamProcessorBase.prototype.xpVersionMetricsKit = function xpVersionMetricsKit() {
    return info.version;
};

/**
 * The versions and names, and delegate dependencies of delegates attached to MetricsKit
 * @example
 *  // If a delegate with the same name/version value is added
 *  // to the same target multiple times, (such as a case where
 *  // portions of one delegate are attached separately to a target)
 *  // each delegate is only represented
 *  // once per 'level' of delegate children
 *  [{
 *      version: '1.2.3',
 *      name: '@amp-metrics/mt-metricskit-delegates-itml'
 *   }
 *   {
 *      version: '3.2.1',
 *      name: '@amp-metrics/mt-metricskit-delegates-html',
 *      delegates:[{
 *          version: '2.1.3',
 *          name: '@amp-metrics/mt-metricskit-delegates-html-ios'
 *      }]
 *  }]
 * @returns {Array} Info of delegates attached to MetricsKit
 * @overridable //this should be changed to not be overridable
 */
ClickstreamProcessorBase.prototype.xpDelegatesInfo = function xpDelegatesInfo() {
    var delegateTree = delegatesInfo.getStoredDelegateObject(this);
    var delegateChildren = delegateTree && delegateTree.delegates;
    // If no delegates have been attached to MetricsKit,
    // return undefined so the field is removed from the event
    return delegateChildren ? delegateChildren : undefined;
};

/*
 *  src/metrics/event_handlers/buyConfirmed.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * <p>
 * PLEASE READ:
 * What follows is an important discussion of how buys operate in iTunes Stores, and how to accurately collect metrics data during that flow.
 * <p>
 * The typical flow of a "buy" in an iTunes Store is:
 * <ol>
 *     <li>User performs some "buy" action (e.g. click a "buy" button or a "subscribe" button)
 *     <li>JavaScript code then creates some "buyData" (including some "buyParams") needed by the Finance servers in order to execute the buy.
 *     <li>JavaScript code then invokes a native "buy" call such as itms.buy(buyData) or itunes.buy(buyData).
 *     <li>In response to the "buy()" call, the native code returns immediately, making the rest of the procedure asynchronous to the JavaScript code.
 *     <li>Native code then makes an HTTP request to the Finance servers with the buyData
 *     <li>Finance servers then reply with a "success" or "failure" response.
 *     <li>When Finance response comes back from Finance, the native code will invoke a JavaScript callback such as "onBuy(buyInfo)".
 *     <li>The "buyInfo" parameter may contain a "result" value (buyInfo.result).
 *     <li>JavaScript code checks buyInfo.return and if present and non-zero/non-null typically invokes (or publishes) a "buyConfirmed" JavaScript event, and if not, invokes (or publishes) a "buyFailed" event.
 *     <li>Within that "buyConfirmed" callback function (perhaps subscribed to), is where the metrics "buyConfirmed" event should be created a and recorded.
 * </ol>
 * </p>
 * That is the <i>typical</i> flow. But things can go wrong.
 * The Finance servers can, for example, in the response to the "buy" request, instruct the native client code to "detour" the user through a Finance flow such as credit card validation, terms of service agreement, etc.
 * When that occurs, the native code <i>will invoke the JavaScript "onBuy" function with a result value indicating buy failure!</i>.
 * However, the buy may not have "really" failed... after the user completes the Finance flow, the "buy" request might eventually succeed, in which case the native code is notified and it will call the JavaScript client's "onBuy" callback with a <i>success</i> return value (causing the "buyConfirmed" to be published), even though it has already called it with a failure code!
 * <p>
 * Due to this special case, the metrics code needs to stash away the metrics data in place at the time the user requests the "buy" and then use that data later (perhaps much later) when/if the "buyConfirmed" actually occurs.
 * In order to marry the metrics data from the time of the "buy", to the event returned in any given "buyConfirmed" (remember, it's all asynchronous), the client creates a "clientBuyId" and uses that as a key to store metrics data.
 * It also passes that key as a query param on the "buy" request so that...
 * When/if the "buyConfirmed" callback is finally called, it will contain the "clientBuyId" value which the metrics code can then use to look up the metrics data that was in place at the time of the "buy".
 * <p>
 * This "detoured" "edge case" of users being redirected through Finance flows can happen a significant percentage of the time (possibly 10-20%) so it has to be handled for accurate metrics.
 * <p>
 * MetricsKit attempts to hide as much of this edge-case craziness as possible, and aid in facilitating the handling of it.
 * <p>
 * <b>To properly instrument buyConfirmed events, JavaScript clients should:</b>
 * <ol>
 *     <li>at <b>"buy"</b> time
 *         <ol>
 *             <li> Create a "clientBuyId" via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.createClientBuyId()</i></b>.
 *                  <br>NOTE: each successive call to this function will return a different clientBuyId
 *             <li> Include that value with the "buyParams" via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.clientBuyIdQueryParamString(clientBuyId)</i></b>
 *             <li> Cache all metrics data needed for the (ulitmate) "buyConfirmed" event, keying off that clientBuyId, via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.cacheMetricsBuyData(clientBuyId, metricsBuyData)</i></b>
 *                  <br>Caching the data here ensures that the metrics buy data accurately reflects the user state at the time of the "buy" vs. their state when the asynchronous "buyConfirmed" callback is received.
 *             <li> Invoke the native "itms/iTunes.buy(buyData)" function.
 *             <br>The clientBuyId will be passed through all the subsequent Finance calls, and eventually be returned to the client when the buy finally succeeds or fails.
 *         </ol>
 *     <li>at <b>"buyFailed"</b> time (which will only happen if user gets "detoured" through a Finance flow)
 *         <ol>
 *             <li> notify MetricsKit that the buy may be detoured via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.buyFailureOccurred(clientBuyId)</i></b> (MetricsKit will add a "detoured" flag to the stashed data)
 *         </ol>
 *     <li>at <b>"buyConfirmed"</b> time (regardless of whether or not it previously failed)
 *         <ol>
 *             <li> retrieve the clientBuyId from the buyData included with the "buyConfirmed" native callback, e.g.:
 *             <br>     var clientBuyId = buyInfo.options.clientBuyId;
 *             <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 *             <li> retrieve the cached metrics data via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.uncacheMetricsBuyData(clientBuyId)</i></b>.
 *                  <br><b>IMPORTANT</b>: If cached data is successfully retrieved for the supplied clientBuyId, that data will be removed in order to keep the cache size under control
 *             <li> prepare the data required by the "buyConfirmed" event (be sure to include the "detoured" flag, if present)
 *             <li> create the "buyConfirmed" metrics event via a call to:
 *                  <br><b><i>metrics.eventHandlers.buyConfirmed.metricsData()</i></b>, including the retrieved cached metrics data.
 *         </ol>
 * </ol>
 *
 * JavaScript clients should
 *
 * @delegatable
 * @constructor
 */
var BuyConfirmed = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

BuyConfirmed.prototype = Object.create(ClickStreamEventHandler.prototype);
BuyConfirmed.prototype.constructor = BuyConfirmed;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} delegate Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
BuyConfirmed.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed buyConfirmed, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}; someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {map} key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
BuyConfirmed.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @returns {array} all the fields that this eventHandler knows about
 */
BuyConfirmed.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
BuyConfirmed.prototype.eventType = function (callerSuppliedEventFields) {
    return 'buyConfirmed';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
BuyConfirmed.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * This function is used as a cacheKey to store metrics data when the user initiates a "buy" and to retrieve that information if the buy "fails" by virtue of the user
 * being forced through, e.g., a Finance flow (CC validation, TOS acceptance, etc.), and then later a "buySuccess" (buyConfirmed) comes through, this value allows
 * the client application to bind to the metrics data that would have been included if the buy had initially succeeded.
 * @returns {number} returns a unique integer value with each call. The uniqueness only last for a single JavaScript "session" (it is merely an incremented value)
 */
BuyConfirmed.prototype.createClientBuyId = function () {
    var newClientId = null;
    var environment = this._processor.system.environment;
    var previousClientBuyId = environment.sessionStorageObject().getItem('mtMetricsKit_previousClientBuyId');

    // May coerce type of previousClientBuyId to Number, NaN result should be reset to 1
    newClientId = ++previousClientBuyId;
    if (!previousClientBuyId) {
        this._processor.system.logger.warn(
            'Metrics: buyConfirmed.createClientBuyId: clientBuyId did not exist or was of incorrect type, reset to 1.'
        );
        newClientId = 1;
    }
    // We use sessionStorage in case our page/JS context goes away and then comes back, we continue where we left off.
    environment.sessionStorageObject().setItem('mtMetricsKit_previousClientBuyId', newClientId);

    return newClientId;
};

// NOTE: I know this method is a trivial convenience and is not so helpful to callers, but what it *does* do is that its existence makes it explicit to callers that clientBuyId needs to be added to their buParams query parameters
//       It also leaves the name of that query param under our control, preventing errors and allowing for transparent changes in the future.
/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * Convenience method for creating the appropriate query param string to include with the "buyParams" on a typical "itms/iTunes.buy(buyInfo)" call
 * @param {number} clientBuyId is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 * @returns {String} a query param string with "clientBuyId" as a key and the value of the passed-in "clientBuyId" as a value, e.g. "&clientBuyId=2"
 * <br>NOTE: The returned string is always prefaced with an ampersand (&), never a question mark (?)
 * @example
 *     var clientBuyId = metrics.eventHandlers.buyConfirmed.createClientBuyId();
 *     buyData.offers[i].buyParams = buyData.offers[i].buyParams + "&someBuyParam=" + someBuyParamValue + metrics.eventHandlers.buyConfirmed.clientBuyIdQueryParamString(clientBuyId(clientBuyId);
 */
BuyConfirmed.prototype.clientBuyIdQueryParamString = function (clientBuyId) {
    return '&clientBuyId=' + clientBuyId;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methods</i>
 * <i>NOTE: This code is not actually used in the generation of "buyConfirmed" events, but still seems like the best home for it.</i>
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * Convenience method for creating the appropriate query param string to include with the "buyParams" on a typical "itms/iTunes.buy(buyInfo)" call
 * @param {String} pageId is the pageId of the page where the buy originated.
 * @param {String} pageType is the pageType of the page where the buy originated.
 * @param {String} pageContext is the pageContext of the page where the buy originated.
 * @param {String} (optional) topic is the topic that will be used to send "dialog" events to if dialogs are presented as a result of the "buy()" call. If omitted, it will default to "xp_its_main"
 * @param {varargs} (optional) callerSuppliedBuyParamsMapsN a variable number of Object arguments from 0-N,
 *                             each containing key/value pairs representing buy parameters to include in
 *                             the returned string
 * @returns {Promise} a Promise that returns an unescaped query param string with 'mt' prefixed keys and the value of the passed-in parameters, plus 'mtPrevPage', derived from the
 * MetricsKit-cached pageHistory (see page event documentation)
 * - mtPrevPage (The previous page, using the pageHistory field)
 * - mtPageType (The pageType field of the page from which the purchase occurs)
 * - mtPageId (The pageId field of the page from which the purchase occurs).  Figaro can use this to ensure that the app being purchased shares an ID with the product page.
 * - mtPageContext (The pageContext field of the page from which the purchase occurs)
 * - mtTopic (The context of an event (e.g. “xp_its_main”).)
 * - mtRequestId (A client generated UUID for every request, to be used in visit stitching to stitch client side event together with server side buy.)
 * Refer to base field documentation for undocumented fields below
 * - mtApp
 * - mtEventTime
 * - mtClientId
 * e.g. "&mtPrevPage=Picker_Welcome&mtPageId=Subscribe&pageType=Picker&pageContext=ForYou"
 * <br>NOTE: The returned string is always prefaced with an ampersand (&), never a question mark (?)
 * @example
 *     var metricsBuyParamsString = await metrics.eventHandlers.buyConfirmed.metricsBuyParamsString(pageId, pageType, pageContext, "xp_its_main", { mtHardwareModel: "iPhone", extRefApp2: "com.apple.Mail" });
 *     buyData.offers[i].buyParams = buyData.offers[i].buyParams + "&someBuyParam=" + someBuyParamValue + "&" + metricsBuyParamsString;
 */
BuyConfirmed.prototype.metricsBuyParamsString = function (
    pageId,
    pageType,
    pageContext,
    topic /*, callerSuppliedBuyParamsMapsN(varargs)*/
) {
    var base = this._processor.eventHandlers.base;
    var page = this._processor.eventHandlers.page;
    var callerSuppliedBuyParamsMapsArray = Array.prototype.slice.call(arguments, 4);
    var pageHistory = page.pageHistory();
    var clientIdPromise = base.clientId();
    var mtPrevPage;

    if (Array.isArray(pageHistory)) {
        if (pageHistory.length >= 2) {
            mtPrevPage = pageHistory[pageHistory.length - 2];
        }
    } else {
        this._processor.system.logger.warn('MetricsKit: metricsBuyParamsString: pageHistory is not an Array');
    }

    return Promise.resolve(clientIdPromise).then(
        function (clientId) {
            var buyParams = {
                mtApp: base.app(callerSuppliedBuyParamsMapsArray),
                mtEventTime: Date.now(),
                mtHardwareBrand: base.hardwareBrand(callerSuppliedBuyParamsMapsArray),
                mtHardwareFamily: base.hardwareFamily(callerSuppliedBuyParamsMapsArray),
                mtHardwareModel: base.hardwareModel(callerSuppliedBuyParamsMapsArray),
                mtHostApp: base.hostApp(callerSuppliedBuyParamsMapsArray),
                mtHostAppVersion: base.hostAppVersion(callerSuppliedBuyParamsMapsArray),
                mtOs: base.os(callerSuppliedBuyParamsMapsArray),
                mtOsBuildNumber: base.osBuildNumber(callerSuppliedBuyParamsMapsArray),
                mtOsVersion: base.osVersion(callerSuppliedBuyParamsMapsArray),
                mtPageId: pageId,
                mtPageType: pageType,
                mtPageContext: pageContext,
                mtTopic: topic || 'xp_its_main',
                mtPrevPage: mtPrevPage,
                mtRequestId: string$1.uuid(),
                mtClientId: clientId
            };

            reflect$1.extend.apply(reflect$1, [buyParams].concat(callerSuppliedBuyParamsMapsArray));

            // NOTE: if any of these fields are null or "undefined",
            // they will be omitted in the "paramString()" function.
            return string$1.paramString(buyParams);
        }.bind(this)
    );
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * <i><b>IMPORTANT</b>: If this method successfully retrieves data for the supplied clientBuyId, that data will be removed in order to keep the cache size under control
 * Called at the time a user initiates a "buy" (e.g. typically immediately before the itms/iTunes.buy(buyData) calls)
 * This function is used to serialize (to string) and cache metrics data when the user initiates a "buy".
 * This data will be retrieved later during the "buyConfirmed" native callback (via the "uncacheMetricsBuyData()" function) and ensures that the metrics buy data accurately reflects the user state at the time of the "buy" vs. their state when the asynchronous "buyConfirmed" callback is received.
 * For example, the user may have been forced through a Finance flow (CC validation, TOS acceptance, etc.) and then later a "buySuccess" (buyConfirmed) comes through.
 * @param {number} clientBuyId is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 * @param {object} metricsBuyData is the value returned by the "createClientBuyId()". Remember to only call that method once, as it returns a different value each time.
 */
BuyConfirmed.prototype.cacheMetricsBuyData = function (clientBuyId, metricsBuyData) {
    var environment = this._processor.system.environment;
    // Since these methods are similarly named, let's just help out the caller by checking...
    if (arguments.length != 2) {
        this._processor.system.logger.error(
            'buyConfirmed.cacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to retrieve cached data instead of setting it, which would be a call to uncacheMetricsBuyData(clientBuyId)?'
        );
    } else {
        // sessionStorage only accepts string values...
        var serializedData = JSON.stringify(metricsBuyData);
        environment
            .sessionStorageObject()
            .setItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId, serializedData);
    }
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time JavaScript receives a "buyConfirmed" callback from the native code.
 * This function is used to deserialize (from string) and return the metrics data that was cached when the user initiated the "buy" via the cacheMetricsBuyData() function.
 * This data should be the data used to include when creating the buyConfirmed event via the metrics.eventHandlers.buyConfirmed.metricsData() function.
 * @param {number} clientBuyId is retrieved from the buyData included with the "buyConfirmed" native callback, e.g.:
 * <br>     var clientBuyId = buyInfo.options.clientBuyId;
 * <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 * @returns {object} the same data that was initially stored with this clientBuyId at itms/iTunes.buy() time via the call to: "cacheMetricsBuyData()"
 * If no data is found for this clientBuyId, "null" will be returned (typically that should never happen)
 */
BuyConfirmed.prototype.uncacheMetricsBuyData = function (clientBuyId) {
    var returnValue = null;
    var environment = this._processor.system.environment;

    // Since these methods are similarly named, let's just help out the caller by checking...
    if (arguments.length != 1) {
        this._processor.system.logger.error(
            'buyConfirmed.uncacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to set cached data instead of retrieving it, which would be a call to cacheMetricsBuyData(clientBuyId, metricsBuyData)?'
        );
    } else {
        // sessionStorage only accepts string values...
        var serializedData = environment
            .sessionStorageObject()
            .getItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId);

        if (serializedData) {
            returnValue = JSON.parse(serializedData);
            environment.sessionStorageObject().removeItem('mtMetricsKit_metricsBuyData_for_clientBuyId_' + clientBuyId);
        }
    }
    return returnValue;
};

/**
 * <i>NOTE: Please read the full description of the "buy" process at the top of this page before attempting to utilize these methdos</i>
 * Called at the time JavaScript receives a "buyFailed" callback from the native code.
 * This function is used to flag "buys" that have been "detoured" through a Finance flow with the "detoured=true" flag.
 * If a buy fails (which is why "buyFailed" would be called) but then later succeeds (after a Finance detour), we will have set the "detoured" flag by virtue of this call.
 * @param {number} clientBuyId is retrieved from the buyData included with the "buyFailed" native callback, e.g.:
 * <br>     var clientBuyId = buyInfo.options.clientBuyId;
 * <br> This is the same clientBuyId that was supplied as a query parameter during the initial itms/iTunes.buy() call and is plumbed through any Finance flows that occurred.
 */
BuyConfirmed.prototype.buyFailureOccurred = function (clientBuyId) {
    var uncacheMetricsBuyData = this.uncacheMetricsBuyData(clientBuyId);

    if (uncacheMetricsBuyData) {
        uncacheMetricsBuyData.detoured = true;
        // Put it back, since a) we added a field and b) asking for it removed it.
        this.cacheMetricsBuyData(clientBuyId, uncacheMetricsBuyData);
    }
};

/*
 *  src/metrics/event_handlers/click.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

// TODO: move to utils-private
var safeJSONParse = function safeJSONParse(text) {
    var returnValue = null;

    try {
        returnValue = JSON.parse(text);
    } catch (e) {
        logger.error('MetricsKit: error parsing click data - ' + e);
    }

    return returnValue;
};

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Click = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Click.prototype = Object.create(ClickStreamEventHandler.prototype);
Click.prototype.constructor = Click;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {Object} targetElement The element from which the click event originated
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * @overridable
 */
Click.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext,
    targetElement /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var argumentsArray = [pageId, pageType, pageContext];
    var utils = this._processor.utils;

    if (targetElement) {
        argumentsArray.push({
            location: utils.eventFields.buildLocationStructure(targetElement, this.locationDataForElement)
        });
        argumentsArray.push(this.dataForElement(targetElement) || {});
    }
    argumentsArray = argumentsArray.concat(Array.prototype.slice.call(arguments, 4));

    return this.processMetricsData.apply(this, argumentsArray);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Click.prototype.knownFields = function knownFields() {
    var knownFields = [
        'actionContext',
        'actionDetails',
        'actionType',
        'actionUrl',
        'eventType',
        'eventVersion',
        'impressions',
        'location',
        'targetId',
        'targetType',
        'positionX',
        'positionY',
        'xpViewablePercentage'
    ];

    return knownFields;
};

/**
 * The parsed click data that was attached to a clicked element
 * @param {Object} targetElement The clicked element
 * @return {Object} the parsed click data that was attached to the element as a data attribute, if present and valid, otherwise null
 * @overridable
 */
Click.prototype.dataForElement = function dataForElement(element) {
    var returnValue = null;

    if (element && reflect$1.isFunction(element.hasAttribute) && reflect$1.isFunction(element.getAttribute)) {
        var clickDataAttribute = this.dataAttribute();
        if (element.hasAttribute(clickDataAttribute)) {
            returnValue = safeJSONParse(element.getAttribute(clickDataAttribute));
        }
    }

    return returnValue;
};

/**
 * The data attribute used to attach click data to DOM-like elements in the view model
 * @returns {String}
 * @overridable
 */
Click.prototype.dataAttribute = function dataAttribute() {
    return 'data-metrics-click';
};

/**
 * The relevant location dictionary for an element
 * @param {Object} element an element in the view heirarchy
 * @return {Object} the location data for the element, if present and valid, otherwise null
 *     The default implementation looks for a data attribute called 'data-metrics-location'
 *     and, if present, parses the attribute into a dictionary, and adds the elements' position
 *     within its parent container as a field called 'locationPosition'
 * @overridable
 */
Click.prototype.locationDataForElement = function locationDataForElement(element) {
    var parentNode = element.parentNode;
    var position = 0;
    var location = null;

    var siblingElements;
    var sibling;
    var siblingLocationInfo;
    var siblingLocationType;

    // if this element has a location type defined (in other words, it has a semantic value from the end user
    // point of view like shelf, lockup etc) then add it to the location stack otherwise don't.
    // for ex. we may have a bunch of <section> elements in our dom tree but there is no point in including
    // them in the location stack
    if (element.hasAttribute && element.hasAttribute('data-metrics-location')) {
        location = safeJSONParse(element.getAttribute('data-metrics-location'));
        if (location.locationType) {
            if (parentNode) {
                // determine our location in the children array of our parent
                siblingElements = parentNode.childNodes;
                for (var i = 0; i < siblingElements.length; i++) {
                    // ITML childNodes list uses .item(i) accessor instead of [i]
                    sibling =
                        (typeof siblingElements.item === 'function' && siblingElements.item(i)) || siblingElements[i];
                    siblingLocationInfo =
                        sibling.hasAttribute && sibling.hasAttribute('data-metrics-location')
                            ? safeJSONParse(sibling.getAttribute('data-metrics-location'))
                            : undefined;
                    siblingLocationType = siblingLocationInfo ? siblingLocationInfo.locationType : undefined;
                    if (siblingLocationType) {
                        if (sibling === element) {
                            // we now know the position of the element, so stop here
                            break;
                        } else {
                            // we consider all siblings that have the data-metrics-location attribute and the same parent container as the target element
                            // for calculating position. for ex. on a grouping page, we may have 2 swooshes, followed by a title text div and then
                            // one more swoosh. We count the preceding swooshes and the title text div sibling element when calculating the position
                            // of the 3rd swoosh. The position of the last swoosh should be '3' (with '0' based index).
                            position++;
                        }
                    }
                }
            }
            location.locationPosition = position;
        }
    }

    return location;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Click.prototype.eventType = function (callerSuppliedEventFields) {
    return 'click';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Click.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 4;
};

/**
 * A list of flattened impression objects for this event
 * Default behavior assumes the impressions have already been flattened and just returns them, but clients can override this with their own flattening implementation
 * @returns {Array} an array of impression objects, or undefined if no event fields were provided by the caller
 * @overridable
 */
Click.prototype.impressions = function impressions(callerSuppliedEventFields) {
    return callerSuppliedEventFields ? callerSuppliedEventFields.impressions : undefined;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * @returns {number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
Click.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    return this._processor.eventHandlers.base.xpViewablePercentage(callerSuppliedEventFields);
};

/*
 *  src/metrics/event_handlers/dialog.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Dialog = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Dialog.prototype = Object.create(ClickStreamEventHandler.prototype);
Dialog.prototype.constructor = Dialog;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Dialog.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed dialog, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Dialog.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Dialog.prototype.knownFields = function knownFields() {
    var knownFields = ['buttons', 'code', 'details', 'message', 'type', 'eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Dialog.prototype.eventType = function (callerSuppliedEventFields) {
    return 'dialog';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Dialog.prototype.eventVersion = function (callerSuppliedEventFields) {
    // Since these have an additional field "type" beyond eventVersion 1 (sent via server-requested "GET" URL ping in MXPFailure.java)
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 2;
};

/*
 *  src/metrics/event_handlers/enter.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Enter = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Enter.prototype = Object.create(ClickStreamEventHandler.prototype);
Enter.prototype.constructor = Enter;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Enter.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed enter, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Enter.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Enter.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'extRefUrl', 'osLanguages', 'refApp', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Enter.prototype.eventType = function (callerSuppliedEventFields) {
    return 'enter';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Enter.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * OS language preferences; a string array of language IDs, ordered in descending preference
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke its accessor, if one is available, in case *its* value is derived or massaged.
 * @returns {Array} a list of preferred languages (strings) e.g. ['en-US', 'fr-CA']
 * @overridable
 */
Enter.prototype.osLanguages = function osLanguages(callerSuppliedEventFields) {
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.osLanguages) ||
        this._processor.system.environment.osLanguages()
    );
};

/*
 *  src/metrics/event_handlers/exit.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Exit = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Exit.prototype = Object.create(ClickStreamEventHandler.prototype);
Exit.prototype.constructor = Exit;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Exit.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed exit, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Exit.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Exit.prototype.knownFields = function knownFields() {
    var knownFields = ['destinationUrl', 'eventType', 'eventVersion', 'type'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Exit.prototype.eventType = function (callerSuppliedEventFields) {
    return 'exit';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Exit.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/flexible.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Flexible = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Flexible.prototype = Object.create(ClickStreamEventHandler.prototype);
Flexible.prototype.constructor = Flexible;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Creates a simple map object (dictionary)
 * @param {String} eventType required for all event creation.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.flexible.metricsData('anEventType', {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns {Promise} A promise that will return key/value pairs of all event fields, merged and cleaned (removes keys that are typeof 'function', keys with 'null' values, keys with 'undefined' values)
 * WARNING: The Promise may return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Flexible.prototype.metricsData = function (eventType /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    var eventData = [undefined, undefined, undefined]; // leave page fields undefined

    // include eventType so it gets processed
    eventData.push({ eventType: eventType });

    var callerSuppliedEventFieldsMapsArray = Array.prototype.slice.call(arguments, 1);
    eventData = eventData.concat(callerSuppliedEventFieldsMapsArray);

    return this.processMetricsData.apply(this, eventData);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Flexible.prototype.knownFields = function knownFields() {
    var knownFields = ['eventTime', 'eventType'];

    return knownFields;
};

/**
 * A flag indicating whether this event should include base fields. Defaults to false for flexible events.
 * @returns {Boolean}
 * @overridable
 */
Flexible.prototype.mtIncludeBaseFields = function mtIncludeBaseFields() {
    return false;
};

/**
 * The time (UTC) in milliseconds at which this event happened.
 * This field is central to determining the sequence of user events
 * Use online epoch converter to test your values.
 * @example 1437356433388 (http://www.epochconverter.com converts that to:  July 19, 2015 at 6:40:33 PM PDT GMT-7:00 DST)
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @returns {number} the time (UTC) in milliseconds at which this event happened
 * @overridable
 */
Flexible.prototype.eventTime = function eventTime(callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventTime) || Date.now();
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Flexible.prototype.eventType = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventType) || undefined;
};

/*
 *  src/metrics/event_handlers/impressions.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Impressions = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Impressions.prototype = Object.create(ClickStreamEventHandler.prototype);
Impressions.prototype.constructor = Impressions;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Impressions.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Impressions.prototype.metricsData = function (
    pageId,
    pageType,
    pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Impressions.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion', 'impressions', 'xpViewablePercentage', 'xpViewableThreshold'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Impressions.prototype.eventType = function (callerSuppliedEventFields) {
    return 'impressions';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Impressions.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 3;
};

/**
 * A list of flattened impression objects for this event
 * Default behavior assumes the impressions have already been flattened and just returns them, but clients can override this with their own flattening implementation
 * @returns {Array} an array of impression objects, or undefined if no event fields were provided by the caller
 * @overridable
 */
Impressions.prototype.impressions = function impressions(callerSuppliedEventFields) {
    return callerSuppliedEventFields ? callerSuppliedEventFields.impressions : undefined;
};

/**
 * The percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * This field should be based on the client's most recent config value of "viewablePercentage".
 * @returns {number} the percentage, from 0 to 1, that an item should be on screen before being considered impressionable
 * @overridable
 */
Impressions.prototype.xpViewablePercentage = function xpViewablePercentage(callerSuppliedEventFields) {
    var base = this._processor.eventHandlers.base;
    return base.xpViewablePercentage(callerSuppliedEventFields);
};

/**
 * The continuous duration, in milliseconds, that an item should be on screen before being considered impressed
 * This field should be based on the client's most recent config value of "viewableThreshold".
 * This is valuable for problem analysis because it indicates if and how clients are honoring the "viewableThreshold" value
 * they were supplied with.
 * This cannot be a "passthrough" field, because it can change (via new config) during program execution, so the value
 * in effect at event creation time is what is needed.
 * @example 1000
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @returns {number} the continuous duration, in milliseconds, that an item should be on screen before being considered impressed
 * @overridable
 */
Impressions.prototype.xpViewableThreshold = function xpViewableThreshold(callerSuppliedEventFields) {
    var config = this._processor.config;
    return (
        (callerSuppliedEventFields && callerSuppliedEventFields.xpViewableThreshold) ||
        config.value('impressions.viewableThreshold')
    );
};

/*
 *  src/metrics/event_handlers/media.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "media" fields + all of the "base" events common to all metrics events.
 * To override any functionality in this class, use the "utils.override() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Media = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Media.prototype = Object.create(ClickStreamEventHandler.prototype);
Media.prototype.constructor = Media;

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Media.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.media.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Media.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Media.prototype.knownFields = function knownFields() {
    var knownFields = [
        'eventType',
        'eventVersion',
        'id',
        'idType',
        'type',
        'typeDetails',
        'actionType',
        'actionDetails',
        'url',
        'duration',
        'position'
    ];
    return knownFields;
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate())
 */

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Media.prototype.eventType = function (callerSuppliedEventFields) {
    return 'media';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Media.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/page.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the "page" fields + all of the "base" events common to all metrics events.
 * To override any functionality in this class, use the "utils.override() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Page = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
    // @private
    this.pageHistoryCache = [];
};

Page.prototype = Object.create(ClickStreamEventHandler.prototype);
Page.prototype.constructor = Page;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Page.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Page.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Page.prototype.knownFields = function knownFields() {
    var knownFields = [
        'eventType',
        'eventVersion',
        'extRefUrl',
        'hostApp',
        'refApp',
        'refUrl',
        'requestStartTime',
        'responseStartTime',
        'responseEndTime',
        'pageHistory',
        'pageLoadTime',
        'pageRenderTime',
        'searchFilters',
        'searchTerm'
    ];

    return knownFields;
};

// ********************* ACCESSOR FUNCTIONS *********************
/**
 * We create accessor functions for every data field because:
 * 1. Cleans/simplifies all methods that use it.
 * 2. Facilitates writing test case shims
 * 3. Allows specific feature suppliers to be overridden (via setDelegate())
 */

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Page.prototype.eventType = function (callerSuppliedEventFields) {
    return 'page';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Page.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/**
 * If a value for this accessor's field exists in "callerSuppliedEventFields", the accessor may want to honor the caller's desire and return that, iff no massaging is needed.
 * Returns an array of the past <= 5 values of 'page' fields from prior page events,
 * storing the current value for use in the next request
 * @param {Map} callerSuppliedEventFields - NOTE: If you want to use one of these fields to help derive *this* eventField, you should
 * invoke it's accessor, if one is available, in case *it's* value is derived or massaged.
 * @return {Array} The past 5 or fewer page event's 'page' fields, *not including* the current page.
 */
Page.prototype.pageHistory = function pageHistory(callerSuppliedEventFields) {
    var returnValue;

    callerSuppliedEventFields = callerSuppliedEventFields || {};
    if (callerSuppliedEventFields.pageHistory) {
        returnValue = callerSuppliedEventFields.pageHistory;
    } else {
        returnValue = this.pageHistoryCache.slice(0); // returns a clone
        var currentPageName = callerSuppliedEventFields.page;

        if (currentPageName) {
            if (this.pageHistoryCache.length >= 5) {
                this.pageHistoryCache.shift();
            }
            this.pageHistoryCache.push(currentPageName);
        }
    }
    return returnValue;
};

/*
 *  src/metrics/event_handlers/search.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Search = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Search.prototype = Object.create(ClickStreamEventHandler.prototype);
Search.prototype.constructor = Search;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Search.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. pageId, pageType, pageContext)
 * @param {String} pageId required for all event creation. Indicates the id of the page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * The type of ID may vary (e.g. adam id, grouping id, result id, etc), but is generally
 * the identifier in some persistent store. Search Results pages may have a pageId which refers to their specific dataSet,
 * otherwise known as dataSetId. If the page is better identified by a descriptive string rather than a content ID,
 * this field may be hard-coded, but it should be unique within the set of pages displayable by the app.
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client.
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageType required for all event creation. Indicates the type of page this event took place on.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * This value should represent the group of pages (e.g. "Genre", “Album”, “Grouping”, "Picker", "Recommendations", "Feed",
 * "Search", "Subscribe", etc.).
 * If an application is not client/server "page" oriented (where the client needs to request data from the server for each "page" of the app), then
 * this field would be generated by the client (potentially being hard-coded).
 * Note: A unique "page" value will created by concatenating pageType+"_"+pageId
 * @param {String} pageContext required for all event creation. Indicates the context within which a page is viewed.
 * This value *will* be overridden if found in any of the provided callerSuppliedEventFieldsMapN dictionaries, which is consistent with later dictionary fields overriding earlier ones.
 * Contexts usually provide independent streams of activity and can typically appear as UI "tab" elements or primary navigation elements.
 * @example: iTunes Desktop: “InTheStore” or “Main”.
 * @example: iOS iTunes apps: tab name (e.g. “Featured”, “TopCharts”, etc)
 * @example: iOS Store sheets:  “Sheet” (e.g. AppStore page launched as a sheet within Mail, Springboard’s “Near Me”, Maps’ “Nearby Apps”)
 * @example a "hint", "related" click, "filter" click, etc.
 * If this event is representing a plain typed search, this field's value may be null
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the known page fields will be included
 * @example metrics.eventHandlers.page.metricsData(appData.pageId, appData.pageType, appData.pageContext, element, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Search.prototype.metricsData = function (pageId, pageType, pageContext /*, callerSuppliedEventFieldsMapN(varargs)*/) {
    // TODO:ATHOMPSON: Add back in with ability to add/not add targetElement param
    return this.processMetricsData.apply(this, arguments);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Search.prototype.knownFields = function knownFields() {
    var knownFields = [
        'actionDetails',
        'actionType',
        'actionUrl',
        'eventType',
        'eventVersion',
        'filters',
        'location',
        'targetId',
        'targetType',
        'term'
    ];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Search.prototype.eventType = function (callerSuppliedEventFields) {
    return 'search';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Search.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 2;
};

/*
 *  src/metrics/event_handlers/transaction.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Creates and returns an object (key/value data map (dictionary)) containing all of the fields needed for this metrics event.
 * To override any functionality in this class, use the "setDelegate() method in order to override the specific functions that need customization.
 * @delegatable
 * @constructor
 */
var Transaction = function (metricsKit) {
    ClickStreamEventHandler.apply(this, arguments);
};

Transaction.prototype = Object.create(ClickStreamEventHandler.prototype);
Transaction.prototype.constructor = Transaction;

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Transaction.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Creates a simple map object (dictionary) with all the fields required by Figaro for this event
 * Some fields can be derived by this class itself.
 * Some fields need to be provided by callers (e.g. the transaction fields and values)
 * @param {Map<String:Any>} transactionMetrics key/value pairs associated with this transaction; typically provided in the response from the buyProduct endpoint
 * @param {varargs} callerSuppliedEventFieldsMapN a variable number of Object arguments from 0-N, each containing key/value pairs representing event fields to include with the returned metricsData
 * All event fields will be merged.
 * An attempt will be made to invoke an accessor method for each field, providing the caller the opportunity to override accessor methods.
 * If no accessor method is found, the event field value will be included in the returned metricsData as-is.
 * Later objects take precedence over earlier ones, overriding any field value that may have already been there.
 * If this parameter is null or omitted, only the transaction metrics will be included
 * @example metrics.eventHandlers.transaction.metricsData(buyProductResponseMetrics, {some:"some", known:"known", eventFieldValues:"eventFieldValues"}, someOtherKnownEventValues, appData.someAdditionalBaseFieldValues);
 * @returns key/value pairs of all event fields + "base" fields required by Figaro.
 * WARNING: May return "null" if metrics are disabled via the metrics.disabled config source value, or on error.
 * @overridable
 */
Transaction.prototype.metricsData = function metricsData(
    transactionMetrics /*, callerSuppliedEventFieldsMapN(varargs)*/
) {
    var argsArray = [null, null, null].concat(Array.prototype.slice.call(arguments));
    return this.processMetricsData.apply(this, argsArray);
};

/**
 * Returns all the fields that this eventHandler knows about.
 * The eventHandler may have accessor functions which derive some of these fields.
 * The "metricsData()" method will use this list of fields to attempt to invoke accessor methods to get field values.
 * Therefore, if callers override this function, and add additional values, and provide accessors for those values, then
 * the "metricsData()" function will ultimately call those accessors as well.
 * @return all the fields that this eventHandler knows about
 */
Transaction.prototype.knownFields = function knownFields() {
    var knownFields = ['eventType', 'eventVersion'];

    return knownFields;
};

/**
 * The type of event this is
 * @returns {String}
 * @overridable
 */
Transaction.prototype.eventType = function (callerSuppliedEventFields) {
    return 'transaction';
};

/**
 * The version of the set of data to be sent up
 * @returns {number}
 * @overridable
 */
Transaction.prototype.eventVersion = function (callerSuppliedEventFields) {
    return (callerSuppliedEventFields && callerSuppliedEventFields.eventVersion) || 1;
};

/*
 *  src/metrics/event_handlers/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

var EventHandlers = function (metricsKitInstance) {
    this.account = new Account(metricsKitInstance);
    this.base = new ClickstreamProcessorBase(metricsKitInstance);
    this.buyConfirmed = new BuyConfirmed(metricsKitInstance);
    this.click = new Click(metricsKitInstance);
    this.dialog = new Dialog(metricsKitInstance);
    this.enter = new Enter(metricsKitInstance);
    this.exit = new Exit(metricsKitInstance);
    this.flexible = new Flexible(metricsKitInstance);
    this.impressions = new Impressions(metricsKitInstance);
    this.media = new Media(metricsKitInstance);
    this.page = new Page(metricsKitInstance);
    this.search = new Search(metricsKitInstance);
    this.transaction = new Transaction(metricsKitInstance);

    delegateExtension.attachDelegateInfo(this.account);
    delegateExtension.attachDelegateInfo(this.base);
    delegateExtension.attachDelegateInfo(this.buyConfirmed);
    delegateExtension.attachDelegateInfo(this.click);
    delegateExtension.attachDelegateInfo(this.enter);
    delegateExtension.attachDelegateInfo(this.exit);
    delegateExtension.attachDelegateInfo(this.flexible);
    delegateExtension.attachDelegateInfo(this.impressions);
    delegateExtension.attachDelegateInfo(this.media);
    delegateExtension.attachDelegateInfo(this.page);
    delegateExtension.attachDelegateInfo(this.search);
    delegateExtension.attachDelegateInfo(this.transaction);
};

/*
 *  src/metrics/utils/event_fields.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Removes duplicate impressions from an array of sibling impressions (i.e. impressions with the same parent) based on whether its index is unique
 * This is needed because the impressions spec:
 *      https://connectme.apple.com/docs/DOC-240953
 * states that:
 *      iii. If items come into view, then go out of view, then come back, they are not counted twice.
 * So, if a user scrolls a swoosh away from a lockup, and then back, so that the lockup is in view again, it will appear twice (with the same index-within-parent) in the impressions-object-tree
 * returned from ITMLKit, but we don't want it included twice, so we remove the dupes here.
 * NOTE: This should never happen with an impressions list retrieved via "itms.snapshotImpressions()" but for caller-simplicity, and since our caller is typically walking the tree already, some of our callers may invoke it even when unnecessary.
 * @param  {Array} impressions An array of impressions to dedupe
 * @return {Array} A set of unique impressions
 */
var dedupeSiblingImpressions = function (impressions) {
    var uniqueIndices = {};
    var dedupedSiblingImpressions = [];
    var currentIndex;
    if (impressions && impressions[0] && impressions[0].index !== undefined) {
        for (var i = 0; i < impressions.length; ++i) {
            currentIndex = impressions[i].index;
            if (!uniqueIndices[currentIndex]) {
                uniqueIndices[currentIndex] = true;
                dedupedSiblingImpressions.push(impressions[i]);
            }
        }
    }
    return dedupedSiblingImpressions;
};

/**
 * These routines are useful for clients to create and access Metrics data and config
 * @constructor
 */
var EventFields$1 = function (processor) {
    // @private
    this._processor = processor;
};

/**
 ************************************ PUBLIC METHODS/IVARS ************************************
 */
/**
 * Uses the provided id to generate its idType
 * @param {String} idString The id to generate a type for
 * @param {String} (Optional) separator id separator, if not provided, this function will return a Promise otherwise the function will return the id string.
 * @return {Promise|String} returns a string of the idType of the provided id if providing separator otherwise returns a Promise
 */
EventFields$1.prototype.getIdType = function (idString, separator) {
    var config = this._processor.config;
    var defaultPrefix = 'its';
    var prefixSeparatorIndex = idString.indexOf('.');
    var prefix = prefixSeparatorIndex !== -1 ? idString.substring(0, prefixSeparatorIndex) : defaultPrefix;

    return reflect$1.isString(separator)
        ? prefix + separator + 'id'
        : config.value('compoundSeparator').then(function (separator) {
              return prefix + separator + 'id';
          });
};

/**
 * This method is the workhorse of all the various eventHandlers.
 * It will take all of the parameters of the callers "metricsData()" method, merge them together,
 * invoke accessors on their known fields, and return the resultant map.
 * @param eventHandler the calling eventHandler
 * @param knownFields the calling eventHandler's list (array) of strings that are that handler's known field values.
 * If the caller has accessors to be invoked, they must be present in the "knownFields" array
 * @returns {Arguments} all of the arguments that the calling eventHandler received.
 * @example:
 * Page.prototype.metricsData = function(pageId, pageType, pageContext, eventFieldsMapN(varargs))
 *      {return utils.eventFields.processMetricsData(this, arguments);
 */
EventFields$1.prototype.processMetricsData = function (
    eventHandler,
    knownFields,
    pageId,
    pageType,
    pageContext,
    callerSuppliedEventFieldsMapsArray
) {
    // Combine all passed-in fields...
    var combinedFieldsMapsArray = [
        {
            pageId: pageId,
            pageType: pageType,
            pageContext: pageContext
        }
    ];
    if (reflect$1.isArray(callerSuppliedEventFieldsMapsArray)) {
        combinedFieldsMapsArray = combinedFieldsMapsArray.concat(callerSuppliedEventFieldsMapsArray);
    }

    return eventFields.processMetricsData(eventHandler, knownFields, true, combinedFieldsMapsArray);
};
/**
 * Returns an object containing the intersection of properties in
 * data and matching string values in the fieldMap property corresponding to 'sectionName'
 * ( e.g. fieldMap.custom[sectionName] is an object containing arrays of strings which
 * correspond to the keys desired in the mappedFields object )
 * @param {Object} data The model data corresponding to element we're mapping fields for
 * @param {String} sectionName Specifies which custom fieldMap to use (eg: 'impressions', 'location', or 'custom')
 * @return {Promise} A Promise that returns an object contains intersection of data and fieldsMap values
 * @example
 * // where impressionFieldsMapSection = {
 * //   impressionType: ['type', 'impressionType'],
 * //   id: ['targetId', 'id']
 * //};
 * applyFieldsMap({type: 'button', id: '123', name: 'playbutton'}, 'impressions')
 * // returns {impressionType: 'button', id: '123'}
 */
EventFields$1.prototype.applyFieldsMap = function (data, sectionName) {
    var config = this._processor.config;
    var self = this;

    if (data && sectionName) {
        return config.value('fieldsMap').then(function (fieldsMap) {
            var mappedFields = {};
            fieldsMap = fieldsMap || {};
            var fieldsMapSection = keyValue.valueForKeyPath(sectionName, fieldsMap, fieldsMap.custom);
            if (fieldsMapSection) {
                var i;
                if (Array.isArray(fieldsMapSection)) {
                    for (i = 0; i < fieldsMapSection.length; ++i) {
                        if (data[fieldsMapSection[i]]) {
                            mappedFields[fieldsMapSection[i]] = data[fieldsMapSection[i]];
                        }
                    }
                } else if (typeof fieldsMapSection === 'object') {
                    for (var key in fieldsMapSection) {
                        for (i = 0; i < fieldsMapSection[key].length; ++i) {
                            var value = keyValue.valueForKeyPath(fieldsMapSection[key][i], data);
                            if (value) {
                                mappedFields[key] = value;
                                break;
                            }
                        }
                    }
                } else {
                    self._processor.system.logger.error(
                        'mt-metricskit-processor-clickstream: incorrect data type provided to applyFieldsMap (only accepts objects and Arrays)'
                    );
                }
            } else {
                self._processor.system.logger.error(
                    'mt-metricskit-processor-clickstream: unable to get fieldsMap from config-source'
                );
            }

            return mappedFields;
        });
    } else {
        if (!data) {
            this._processor.system.logger.error(
                'mt-metricskit-processor-clickstream: No data provided to applyFieldsMap'
            );
        }
        if (!sectionName) {
            this._processor.system.logger.error(
                'mt-metricskit-processor-clickstream: No sectionName provided to applyFieldsMap'
            );
        }
        return Promise.resolve(undefined);
    }
};
/**
 * Creates a deduped & flattened representation of the list of impressions tree nodes provided
 * reassigns some impressions values for use with metrics processing
 * @param {Array} impressions Array of IKJSImpressions objects
 * @param {number} currentId The index at which to increment impresionId off of
 * @return {Promise} A Promise returns impressionsArray array of Objects corresponding to and created from data in impressions
 */
EventFields$1.prototype.flattenImpressions = function (impressions, currentId) {
    var config = this._processor.config;

    // Because this function needs to load "compoundSeparator" from config in the loop and also recursively build impressions.
    // So create the internal flattenImpressions function to make we load the  "compoundSeparator" outside of the function to make the function simple and clean.
    var recursivelyFlattenImpressions = function recursivelyFlattenImpressions(impressions, currentId, separator) {
        var impressionsArray = [];
        var anImpression;
        var impressionData;
        var childrenArray;
        var decodedData;
        var impressionId = currentId || 1;

        if (impressions) {
            impressions = dedupeSiblingImpressions(impressions);
            for (var i = 0; i < impressions.length; i++) {
                anImpression = impressions[i];
                if (typeof anImpression.data === 'string') {
                    try {
                        impressionData = JSON.parse(anImpression.data);
                    } catch (anException) {
                        // Lets' see if the exception happened because someone put URIEncoded data in the impression...
                        decodedData = decodeURIComponent(anImpression.data);
                        try {
                            impressionData = JSON.parse(decodedData);
                        } catch (anotherException) {
                            // So, the error is not [necessarily] due to encoding. Let's not stop the app here by letting this exception propogate, throw the original exception.
                            // (see the discussion about catching exceptions here in this radar: <rdar://problem/23810404> Metricskit: JSON parse error in flattenImpressions
                            this._processor.system.logger.error(
                                'mt-metricskit-processor-clickstream: non-JSON serialized data found on impression object. Cannot parse.',
                                anException
                            );
                        }
                    }
                } else {
                    impressionData = anImpression;
                }
                if (impressionData) {
                    impressionData.impressionTimes = anImpression.timestamps;
                    impressionData.impressionIndex = anImpression.index;
                    if (impressionData.id && !impressionData.idType) {
                        if (anImpression.kind === 'genre') {
                            // Remove when server provides genre id prefixes
                            impressionData.idType = 'label' + separator + 'id';
                        } else {
                            impressionData.idType = this.getIdType(impressionData.id.toString(), separator);
                        }
                    }
                    if (anImpression.parent && anImpression.parent.impressionId !== undefined) {
                        // if no parent, parent === null
                        impressionData.impressionParentId = anImpression.parent.impressionId;
                    }
                    impressionData.impressionId = impressionId;
                    anImpression.impressionId = impressionId; // saves this value for use as parentId
                    ++impressionId;
                    impressionsArray.push(impressionData);
                    if (keyValue.valueForKeyPath('children.length', anImpression) > 0) {
                        childrenArray = recursivelyFlattenImpressions(anImpression.children, impressionId, separator);
                        impressionsArray = impressionsArray.concat(childrenArray);
                        impressionId += childrenArray.length;
                    }
                }
            }
        } else {
            this._processor.system.logger.warn('Fuse-Metrics: No impressions provided to to flattenImpressions');
        }

        return impressionsArray;
    }.bind(this);

    return config.value('compoundSeparator').then(function (separator) {
        return recursivelyFlattenImpressions(impressions, currentId, separator);
    });
};

/**
 * Returns a flat array representing the location of the clicked element
 * @param {Object} targetElement The clicked element, requires attribute data-metrics-location with obj key of locationType
 * @param {Function} locationFn a function that takes an element as an argument and calculates
 *     the location dictionary for that element
 * @return {Array} A flat array representing the location of the target element
 */
EventFields$1.prototype.buildLocationStructure = function buildLocationStructure(targetElement, locationFn) {
    var currentElement = targetElement;
    var locationStack = [];
    var location;

    //loop and add element locations to the the location stack to be returned
    while (currentElement) {
        location = locationFn.call(locationFn, currentElement);
        if (location) {
            locationStack.push(location);
        }

        currentElement = currentElement.parentNode;
    }
    return locationStack;
};

/*
 *  src/network.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2018 Apple Inc. All rights reserved.
 *
 */

/**
 * Network request methods exposed so delegate callers can override
 * @constructor
 */
var Network = function () {};

/**
 * Allows replacement of one or more of this class' functions
 * Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
 * To replace *all* methods of his class, simply have your delegate implement all the methods of this class
 * Your delegate can be a true object instance, an anonymous object, or a class object.
 * Your delegate is free to have as many additional non-matching methods as it likes.
 * It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
 *
 * "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
 * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
 * If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
 * then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
 * but override the "appVersion" method again, this time with their own supplied delegate.
 *
 * NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
 * This allows the delegate to, essentially, call "super" before or after it does some work.
 * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
 * @example:
 * To override one or more methods, in place:
 *      eventRecorder.setDelegate({recordEvent: itms.recordEvent});
 * To override one or more methods with a separate object:
 *      eventRecorder.setDelegate(eventRecorderDelegate);
 *      (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          var eventRecorderDelegate = {recordEvent: itms.recordEvent,
 *                                       sendMethod: 'itms'};
 * To override one or more methods with an instantiated object from a class definition:
 *      eventRecorder.setDelegate(new EventRecorderDelegate());
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
 *                                                          return 'itms';
 *                                                      };
 * To override one or more methods with a class object (with "static" methods):
 *      eventRecorder.setDelegate(EventRecorderDelegate);
 *      (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
 *          function EventRecorderDelegate() {
 *         }
 *         EventRecorderDelegate.recordEvent = itms.recordEvent;
 *         EventRecorderDelegate.sendMethod = function sendMethod() {
 *                                                return 'itms';
 *                                            };
 * @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
 * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
 * otherwise returns false.
 */
Network.prototype.setDelegate = function setDelegate(delegate) {
    return reflect$1.attachDelegate(this, delegate);
};

/**
 * Covers private util network functions for delegation
 */
Network.prototype.makeAjaxRequest = network.makeAjaxRequest;

/*
 *  src/metrics/utils/reflect.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015 Apple Inc. All rights reserved.
 *
 */

/**
 * Object Reflection Primitive Methods (e.g. "Map" type methods)
 * copied from private utils so delegate callers can use them
 * @constructor
 */
var reflect = {
    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */
    /**
     * Replace any "target" methods found on "delegate" with the delegate's version of the method.
     * The replacement function will actually be our own wrapper function with the original function attached as a property called origFunction
     * in case the delegate's replacement method wants to, essentially, call "super"
     * We do delegation this way, vs. checking each time a "target" function is called, because this way we don't pollute the implementation
     * of all the target's functions.
     * Subsequent calls to "attachDelegate" will then replace whatever methods *they* match, including methods that have already been replaced.
     * This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
     * NOTE: Only methods present on "target" will be replaced. If a delegate method is not found on target, "false" will be returned.
     * If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
     * @param target
     * @param delegate
     * @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
     */
    attachDelegate: function attachDelegate(target, delegate) {
        return reflect$1.attachDelegate(target, delegate);
    },

    /**
     * Adds all the fields of the objects in the varargs to the fields in the first parameter, "obj".
     * *All* "hasOwnProperty" fields will be added, including functions and fields with no values.
     * @param {Object} targetObject an object with keys and values. If only one parameter is provided, the return value will be the non-null values of that single object.
     * @param {varargs} sourceObjectN a variable number of Object arguments from 0-N. Each object's fields will be copied into targetObject. Later objects take precedence over earlier ones.
     * @return targetObject (*not* a clone) with the additional fields added..
     */
    extend: function extend(targetObject /* , ...sourceObjectN(varargs) */) {
        return reflect$1.extend.apply(reflect$1, arguments);
    },

    /**
     * Bind the execution context of the methods of given Object to itself.
     * NOTE: Only bind the functions that are owned by the parameter object
     * @param {Object} targetObject an object with keys and values.
     */
    bindFunctionsContext: function bindFunctionsContext(targetObject) {
        if (targetObject) {
            for (var key in targetObject) {
                if (typeof targetObject[key] === 'function') {
                    targetObject[key] = targetObject[key].bind(targetObject);
                }
            }
        }
    }
};

/*
 *  src/metrics/utils/string.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2017 Apple Inc. All rights reserved.
 *
 */

/**
 * String related util methods
 * copied from private utils so delegate callers can use them
 * @constructor
 */
var string = {
    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */
    /**
     * Parses a user agent string for a particular product name and returns its version
     * @param {String} userAgent that conforms with RFC 7231 section 5.5.3 regarding User-Agents
     * @param {String} (optional) productName the name of a product identifier to search for e.g. 'iTunes'; if omitted, defaults to the first identifier
     * @return {String} the version of the product, or null if none found
     * @example
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34') returns '12.6'
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34', 'AppleWebKit') returns '603.1.30.0.34'
     *      productVersionFromUserAgent('iTunes/12.6 (Macintosh; OS X 10.12.4) AppleWebKit/603.1.30.0.34', 'Macintosh') returns null
     *          (strings contained in parentheses are counted as comments, not product identifiers)
     */
    versionStringFromUserAgent: function versionStringFromUserAgent(userAgent, productName) {
        return string$1.versionStringFromUserAgent(userAgent, productName);
    }
};

/*
 *  src/metrics/utils/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2015-2016 Apple Inc. All rights reserved.
 *
 */

var Utils = function Utils(mtkitInstance) {
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.delegateExtension = delegateExtension;
    // assign new eventFields instance to utils, to give eventFields the metricsKit instance context.
    this.eventFields = new EventFields$1(mtkitInstance);
    // bind the context to eventHandlers to avoid losing the runtime context if the client assign function to a variable.
    reflect.bindFunctionsContext(this.eventFields);

    // copy keyValue from private utils for historical reasons in case clients are using it
    // this can probably be removed with more research
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.keyValue = keyValue;
    this.network = new Network();
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.reflect = reflect;
    // TODO if no client is using it, maybe it could be removed from Utils class
    this.string = string;
};

/*
 *  src/utils/event_field_accessors/base.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var Base = function (metricsKit) {
    // @private
    this._eventHandler = new Flexible(metricsKit);
};

/**
 ************************************ PUBLIC METHODS ************************************
 */

/**
 * Return the corresponding clientId with the giving status
 * @param {Object} qualifiers
 * @param {Boolean} qualifiers.isSignedIn - A boolean value indicating the returned clientId is for signed-in status or signed-out status.
 * @returns {Promise} A Promise that resolved the clientId, will return null if
 *      1. the entire event is denied by config
 *      2. the clientId is a denied field
 */
Base.prototype.clientId = function clientId(qualifiers) {
    return this._eventHandler
        .metricsData('', qualifiers)
        .toJSON()
        .then(function (eventFields) {
            return eventFields ? eventFields.clientId : null;
        });
};

/*
 *  src/event_fields/index.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2021 Apple Inc. All rights reserved.
 *
 */

var EventFields = function (metricsKitInstance) {
    this.base = new Base(metricsKitInstance);
};

/*
 *  src/metrics/clickstream_processor.js
 *  mt-metricskit-processor-clickstream
 *
 *  Copyright © 2020 Apple Inc. All rights reserved.
 *
 */

/**
 * Supplies a JavaScript entrypoint to metrics functionality
 * Since JavaScript is prototype-based and not class-based, and  doesn't provide an "official" object model, this API is presented as a functional API, but still retains the ability to
 * override and customize functionality via the "setDelegate()" method. In this way, it doesn't carry with it the spare baggage of exposing a bolt-on object model which may
 * differ from a bolt-on (or homegrown) object model already existing in the app.
 * @module src/metrics
 * @param {Object}  delegates - The below interface will be generated by Metrics delegates(mt-metricskit-delegates-*). Clients don't have to generate it by themselves
 *                               For more details, please reference the respective document of mt-metricskit-delegates-*
 * @constructor
 */
var ClickstreamProcessor = function ClickstreamProcessor(delegates) {
    if (!reflect$1.isDefinedNonNull(delegates)) {
        throw new Error('No delegate is provided to ClickstreamProcessor');
    }

    /**
     ************************************ PRIVATE IVARS ************************************
     */

    // @private
    this._initCalled = false;

    // @private
    this._delegatePackage = delegates;

    /**
     ************************************ PUBLIC METHODS/IVARS ************************************
     */

    /**
     * Access the various "system" classes defined in ClickstreamProcessor.
     * These classes are typically system/platform specific
     * These classes can have their functionality replaced either en masse or piecemeal via the setDelegate() method.
     * Available system classes are:
     *      environment
     *      eventRecorder
     *      logger
     * @example: metrics.system.environment.setDelegate(myEnvironmentFunctions)
     * @see setDelegate()
     */
    this.system = new System();

    /**
     * Access the various configuration values.
     * These are basically pretty wrappers on config fields retrieved via the "configValue" method.
     * Note: Must be created in the constructor in order for a client to set a debug source before fetching config with init()
     * @example: metrics.config.isDisabled()
     */
    this.config = this._delegatePackage.config;

    /**
     * Sub-library providing access to all the various eventHandlers of ClickstreamProcessor.
     */
    this.eventHandlers = new EventHandlers(this);

    /**
     * Sub-library providing access to all the various eventFields of ClickstreamProcessor.
     */
    this.eventFields = new EventFields(this);

    /**
     * Sub-library providing various utility functions which are useful when interacting with ClickstreamProcessor
     */
    this.utils = new Utils(this);

    this._constraints = null;
};

/**
 * Initialize ClickstreamProcessor - will register, fetch config, set delegates, etc.
 * NOTE: This API should not be called more than once. Subsequent calls will have no effect (no-op).
 * NOTE 2: This function initializes metrics config values which are required for proper event generation.
 *         This initialization will be asynchronous unless a configSourcesFn is provided.
 *         Events that are generated before initialization have completed will use config defaults.
 *         If clients want to ensure that config is fetched before events are generated,
 *         they can do one of the following when calling clickstreamProcessor.init():
 *                (1) provide a configSourcesFn; in existing clients the config sources function is provided via the metrics.config.setDelegate() API
 *                (2) wait until the init() callback completes before generating and recording any events (Note that when using this method,
 *                    any user actions that occured before the callback completes will have later eventTimes than when they actually occured)
 *
 * ADDITIONAL DESIGN NOTES:
 * Promise/PubSub:
 *     These would require some polyfill or additional module support, which we do not want to bake into our framework.
 *     We will expect that clients will honor the init() contract by not calling it more than once, and we provide a completion callback.
 * Deferring event generation:
 *     We could store a queue of events to generate once we have config. However, this is complex and error prone, and requires
 *     the eventRecorder to have special knowledge that this is happening and knowledge about how to properly generate those events
 *     (for example, the eventTime should reflect the time the deferred event was queued, not the time it was later generated).
 * Using defaults:
 *     Most config values are common to the majority of apps and do not change very much, so in the interest of simplicity,
 *     we choose to fall back to default config values for any events generated before config resolves.
 *     The ingestion server will enrich clientId on events in a batch missing clientId.
 *     As an additional fallback, we store the most recently fetched config in localStorage for any future visits from the same browser.
 *
 *  @returns {Promise} A Promise that resolved the MetricsKit initialization
 */
ClickstreamProcessor.prototype.init = function init() {
    var initPromise = Promise.resolve();
    if (!this._initCalled) {
        this._initCalled = true;

        // set any provided delegates
        if (this._delegatePackage) {
            reflect$1.setDelegates(this.eventHandlers, this._delegatePackage);
            reflect$1.setDelegates(this.system, this._delegatePackage);
            // TODO rdar://92551827 (Add test case for clickstream processor delegate initialization)
            reflect$1.setDelegates(this.utils, this._delegatePackage);
        }

        // Init config
        initializeConfig(this.config);
        initPromise = this._delegatePackage.init();

        this._constraints = new Constraints(this.config, {
            environment: this.system.environment
        });
    }

    return initPromise;
};

/**
 * Release resources from MetricsKit
 */
ClickstreamProcessor.prototype.cleanup = function cleanup() {
    if (this._delegatePackage && reflect$1.isFunction(this._delegatePackage.cleanup)) {
        // cleanup delegate before cleanup config, in case the cleanup method of delegate uses the config
        this._delegatePackage.cleanup();
    }
    cleanupConfig(this.config);
    reflect$1.resetDelegates(this.eventHandlers);
    reflect$1.resetDelegates(this.system);
    reflect$1.resetDelegates(this.utils);
    this.config = null;
    this.system = null;
    this.eventHandlers = null;
    this.utils = null;
    this._delegatePackage = null;
    this._constraints = null;
    this._initCalled = false;
};

export { ClickstreamProcessor };
