@optimizely/optimizely-sdk
Version:
JavaScript SDK for Optimizely X Full Stack
15 lines (13 loc) • 93.7 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).optimizelySdk={})}(this,(function(e){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var t=function(){return(t=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function r(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var n=Array(e),i=0;for(t=0;t<r;t++)for(var o=arguments[t],a=0,s=o.length;a<s;a++,i++)n[i]=o[a];return n}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e,t){return e(t={exports:{}},t.exports),t.exports}var a=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){}return e.prototype.handleError=function(e){},e}();t.NoopErrorHandler=r;var n=new r;t.setErrorHandler=function(e){n=e},t.getErrorHandler=function(){return n},t.resetErrorHandler=function(){n=new r}}));i(a);a.NoopErrorHandler,a.setErrorHandler,a.getErrorHandler,a.resetErrorHandler;var s=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.NOTSET=0]="NOTSET",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARNING=3]="WARNING",e[e.ERROR=4]="ERROR"}(t.LogLevel||(t.LogLevel={}))}));i(s);s.LogLevel;for(var u=o((function(e){var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(t){var r=new Uint8Array(16);e.exports=function(){return t(r),r}}else{var n=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),n[t]=e>>>((3&t)<<3)&255;return n}}})),l=[],c=0;c<256;++c)l[c]=(c+256).toString(16).substr(1);var f,E,d=function(e,t){var r=t||0,n=l;return[n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],"-",n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]],n[e[r++]]].join("")},_=0,g=0;var p=function(e,t,r){var n=t&&r||0,i=t||[],o=(e=e||{}).node||f,a=void 0!==e.clockseq?e.clockseq:E;if(null==o||null==a){var s=u();null==o&&(o=f=[1|s[0],s[1],s[2],s[3],s[4],s[5]]),null==a&&(a=E=16383&(s[6]<<8|s[7]))}var l=void 0!==e.msecs?e.msecs:(new Date).getTime(),c=void 0!==e.nsecs?e.nsecs:g+1,p=l-_+(c-g)/1e4;if(p<0&&void 0===e.clockseq&&(a=a+1&16383),(p<0||l>_)&&void 0===e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");_=l,g=c,E=a;var v=(1e4*(268435455&(l+=122192928e5))+c)%4294967296;i[n++]=v>>>24&255,i[n++]=v>>>16&255,i[n++]=v>>>8&255,i[n++]=255&v;var I=l/4294967296*1e4&268435455;i[n++]=I>>>8&255,i[n++]=255&I,i[n++]=I>>>24&15|16,i[n++]=I>>>16&255,i[n++]=a>>>8|128,i[n++]=255&a;for(var h=0;h<6;++h)i[n+h]=o[h];return t||d(i)};var v=function(e,t,r){var n=t&&r||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||u)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var o=0;o<16;++o)t[n+o]=i[o];return t||d(i)},I=v;I.v1=p,I.v4=v;var h=I,R=o((function(e,t){function r(e){return Object.keys(e).map((function(t){return e[t]}))}Object.defineProperty(t,"__esModule",{value:!0}),t.getTimestamp=function(){return(new Date).getTime()},t.generateUUID=function(){return h.v4()},t.isValidEnum=function(e,t){for(var r=!1,n=Object.keys(e),i=0;i<n.length;i++)if(t===e[n[i]]){r=!0;break}return r},t.groupBy=function(e,t){var n={};return e.forEach((function(e){var r=t(e);n[r]=n[r]||[],n[r].push(e)})),r(n)},t.objectValues=r,t.find=function(e,t){for(var r,n=0,i=e;n<i.length;n++){var o=i[n];if(t(o)){r=o;break}}return r},t.keyBy=function(e,t){var r={};return e.forEach((function(e){var n=t(e);r[n]=e})),r},t.sprintf=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=0;return e.replace(/%s/g,(function(){var e=t[n++],r=typeof e;return"function"===r?e():"string"===r?e:String(e)}))}}));i(R);R.getTimestamp,R.generateUUID,R.isValidEnum,R.groupBy,R.objectValues,R.find,R.keyBy,R.sprintf;var T=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r={NOTSET:0,DEBUG:1,INFO:2,WARNING:3,ERROR:4};function n(e){return"string"!=typeof e?e:("WARN"===(e=e.toUpperCase())&&(e="WARNING"),r[e]?r[e]:e)}var i=function(){function e(){this.defaultLoggerFacade=new c,this.loggers={}}return e.prototype.getLogger=function(e){return e?(this.loggers[e]||(this.loggers[e]=new c({messagePrefix:e})),this.loggers[e]):this.defaultLoggerFacade},e}(),o=function(){function e(e){void 0===e&&(e={}),this.logLevel=s.LogLevel.NOTSET,void 0!==e.logLevel&&R.isValidEnum(s.LogLevel,e.logLevel)&&this.setLogLevel(e.logLevel),this.logToConsole=void 0===e.logToConsole||!!e.logToConsole,this.prefix=void 0!==e.prefix?e.prefix:"[OPTIMIZELY]"}return e.prototype.log=function(e,t){if(this.shouldLog(e)&&this.logToConsole){var r=this.prefix+" - "+this.getLogLevelName(e)+" "+this.getTime()+" "+t;this.consoleLog(e,[r])}},e.prototype.setLogLevel=function(e){e=n(e),R.isValidEnum(s.LogLevel,e)&&void 0!==e?this.logLevel=e:this.logLevel=s.LogLevel.ERROR},e.prototype.getTime=function(){return(new Date).toISOString()},e.prototype.shouldLog=function(e){return e>=this.logLevel},e.prototype.getLogLevelName=function(e){switch(e){case s.LogLevel.DEBUG:return"DEBUG";case s.LogLevel.INFO:return"INFO ";case s.LogLevel.WARNING:return"WARN ";case s.LogLevel.ERROR:return"ERROR";default:return"NOTSET"}},e.prototype.consoleLog=function(e,t){switch(e){case s.LogLevel.DEBUG:console.log.apply(console,t);break;case s.LogLevel.INFO:console.info.apply(console,t);break;case s.LogLevel.WARNING:console.warn.apply(console,t);break;case s.LogLevel.ERROR:console.error.apply(console,t);break;default:console.log.apply(console,t)}},e}();t.ConsoleLogHandler=o;var u=s.LogLevel.NOTSET,l=null,c=function(){function e(e){void 0===e&&(e={}),this.messagePrefix="",e.messagePrefix&&(this.messagePrefix=e.messagePrefix)}return e.prototype.log=function(e,t){this.internalLog(n(e),{message:t,splat:[]})},e.prototype.info=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.namedLog(s.LogLevel.INFO,e,t)},e.prototype.debug=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.namedLog(s.LogLevel.DEBUG,e,t)},e.prototype.warn=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.namedLog(s.LogLevel.WARNING,e,t)},e.prototype.error=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.namedLog(s.LogLevel.ERROR,e,t)},e.prototype.format=function(e){return(this.messagePrefix?this.messagePrefix+": ":"")+R.sprintf.apply(void 0,[e.message].concat(e.splat))},e.prototype.internalLog=function(e,t){l&&(e<u||(l.log(e,this.format(t)),t.error&&t.error instanceof Error&&a.getErrorHandler().handleError(t.error)))},e.prototype.namedLog=function(e,t,r){var n;if(t instanceof Error)return t=(n=t).message,void this.internalLog(e,{error:n,message:t,splat:r});if(0!==r.length){var i=r[r.length-1];i instanceof Error&&(n=i,r.splice(-1)),this.internalLog(e,{message:t,error:n,splat:r})}else this.internalLog(e,{message:t,splat:r})},e}(),f=new i;t.getLogger=function(e){return f.getLogger(e)},t.setLogHandler=function(e){l=e},t.setLogLevel=function(e){e=n(e),u=R.isValidEnum(s.LogLevel,e)&&void 0!==e?e:s.LogLevel.ERROR},t.getLogLevel=function(){return u},t.resetLogger=function(){f=new i,u=s.LogLevel.NOTSET}}));i(T);T.ConsoleLogHandler,T.getLogger,T.setLogHandler,T.setLogLevel,T.getLogLevel,T.resetLogger;var y=o((function(e,t){function r(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}Object.defineProperty(t,"__esModule",{value:!0}),r(a),r(s),r(T)}));i(y);var O=y.ConsoleLogHandler,N=y.getLogger,A=y.setLogLevel,m=y.LogLevel,L=y.setLogHandler,U=y.setErrorHandler,S=y.getErrorHandler,D=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.areEventContextsEqual=void 0,t.areEventContextsEqual=function(e,t){var r=e.context,n=t.context;return r.accountId===n.accountId&&r.projectId===n.projectId&&r.clientName===n.clientName&&r.clientVersion===n.clientVersion&&r.revision===n.revision&&r.anonymizeIP===n.anonymizeIP&&r.botFiltering===n.botFiltering}}));i(D);D.areEventContextsEqual;var V=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultEventQueue=t.SingleEventQueue=void 0;var r=y.getLogger("EventProcessor"),n=function(){function e(e){var t=e.timeout,r=e.callback;this.timeout=Math.max(t,0),this.callback=r}return e.prototype.start=function(){this.timeoutId=setTimeout(this.callback,this.timeout)},e.prototype.refresh=function(){this.stop(),this.start()},e.prototype.stop=function(){this.timeoutId&&clearTimeout(this.timeoutId)},e}(),i=function(){function e(e){var t=e.sink;this.sink=t}return e.prototype.start=function(){},e.prototype.stop=function(){return Promise.resolve()},e.prototype.enqueue=function(e){this.sink([e])},e}();t.SingleEventQueue=i;var o=function(){function e(e){var t=e.flushInterval,r=e.maxQueueSize,i=e.sink,o=e.batchComparator;this.buffer=[],this.maxQueueSize=Math.max(r,1),this.sink=i,this.batchComparator=o,this.timer=new n({callback:this.flush.bind(this),timeout:t}),this.started=!1}return e.prototype.start=function(){this.started=!0},e.prototype.stop=function(){this.started=!1;var e=this.sink(this.buffer);return this.buffer=[],this.timer.stop(),e},e.prototype.enqueue=function(e){if(this.started){var t=this.buffer[0];t&&!this.batchComparator(t,e)&&this.flush(),0===this.buffer.length&&this.timer.refresh(),this.buffer.push(e),this.buffer.length>=this.maxQueueSize&&this.flush()}else r.warn("Queue is stopped, not accepting event")},e.prototype.flush=function(){this.sink(this.buffer),this.buffer=[],this.timer.stop()},e}();t.DefaultEventQueue=o}));i(V);V.DefaultEventQueue,V.SingleEventQueue;var b=o((function(e,t){function r(e){return Object.keys(e).map((function(t){return e[t]}))}Object.defineProperty(t,"__esModule",{value:!0}),t.generateUUID=function(){return h.v4()},t.getTimestamp=function(){return(new Date).getTime()},t.isValidEnum=function(e,t){for(var r=!1,n=Object.keys(e),i=0;i<n.length;i++)if(t===e[n[i]]){r=!0;break}return r},t.groupBy=function(e,t){var n={};return e.forEach((function(e){var r=t(e);n[r]=n[r]||[],n[r].push(e)})),r(n)},t.objectValues=r,t.objectEntries=function(e){return Object.keys(e).map((function(t){return[t,e[t]]}))},t.find=function(e,t){for(var r,n=0,i=e;n<i.length;n++){var o=i[n];if(t(o)){r=o;break}}return r},t.keyBy=function(e,t){var r={};return e.forEach((function(e){var n=t(e);r[n]=e})),r},t.sprintf=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var n=0;return e.replace(/%s/g,(function(){var e=t[n++],r=typeof e;return"function"===r?e():"string"===r?e:String(e)}))},function(e){e.ACTIVATE="ACTIVATE:experiment, user_id,attributes, variation, event",e.DECISION="DECISION:type, userId, attributes, decisionInfo",e.LOG_EVENT="LOG_EVENT:logEvent",e.OPTIMIZELY_CONFIG_UPDATE="OPTIMIZELY_CONFIG_UPDATE",e.TRACK="TRACK:event_key, user_id, attributes, event_tags, event"}(t.NOTIFICATION_TYPES||(t.NOTIFICATION_TYPES={}))}));i(b);var C=b.generateUUID,P=(b.getTimestamp,b.isValidEnum,b.groupBy,b.objectValues),M=(b.objectEntries,b.find,b.keyBy),F=b.sprintf,k=b.NOTIFICATION_TYPES,x=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.sendEventNotification=t.getQueue=t.validateAndGetBatchSize=t.validateAndGetFlushInterval=t.DEFAULT_BATCH_SIZE=t.DEFAULT_FLUSH_INTERVAL=void 0,t.DEFAULT_FLUSH_INTERVAL=3e4,t.DEFAULT_BATCH_SIZE=10;var r=y.getLogger("EventProcessor");t.validateAndGetFlushInterval=function(e){return e<=0&&(r.warn("Invalid flushInterval "+e+", defaulting to "+t.DEFAULT_FLUSH_INTERVAL),e=t.DEFAULT_FLUSH_INTERVAL),e},t.validateAndGetBatchSize=function(e){return(e=Math.floor(e))<1&&(r.warn("Invalid batchSize "+e+", defaulting to "+t.DEFAULT_BATCH_SIZE),e=t.DEFAULT_BATCH_SIZE),e=Math.max(1,e)},t.getQueue=function(e,t,r,n){return e>1?new V.DefaultEventQueue({flushInterval:t,maxQueueSize:e,sink:r,batchComparator:n}):new V.SingleEventQueue({sink:r})},t.sendEventNotification=function(e,t){e&&e.sendNotifications(b.NOTIFICATION_TYPES.LOG_EVENT,t)}}));i(x);x.sendEventNotification,x.getQueue,x.validateAndGetBatchSize,x.validateAndGetFlushInterval,x.DEFAULT_BATCH_SIZE,x.DEFAULT_FLUSH_INTERVAL;var B=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0})}));i(B);var w=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0})}));i(w);var G=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStorageStore=void 0;var r=y.getLogger("EventProcessor"),n=function(){function e(e){var t=e.key,r=e.maxValues,n=void 0===r?1e3:r;this.LS_KEY=t,this.maxValues=n}return e.prototype.get=function(e){return this.getMap()[e]||null},e.prototype.set=function(e,t){var r=this.getMap();r[e]=t,this.replace(r)},e.prototype.remove=function(e){var t=this.getMap();delete t[e],this.replace(t)},e.prototype.values=function(){return b.objectValues(this.getMap())},e.prototype.clear=function(){this.replace({})},e.prototype.replace=function(e){try{window.localStorage&&localStorage.setItem(this.LS_KEY,JSON.stringify(e)),this.clean()}catch(e){r.error(e)}},e.prototype.clean=function(){var e=this.getMap(),t=Object.keys(e),r=t.length-this.maxValues;if(!(r<1)){var n=t.map((function(t){return{key:t,value:e[t]}}));n.sort((function(e,t){return e.value.timestamp-t.value.timestamp}));for(var i=0;i<r;i++)delete e[n[i].key];this.replace(e)}},e.prototype.getMap=function(){try{var e=window.localStorage&&localStorage.getItem(this.LS_KEY);if(e)return JSON.parse(e)||{}}catch(e){r.error(e)}return{}},e}();t.LocalStorageStore=n}));i(G);G.LocalStorageStore;var K=o((function(e,t){var r,i=n&&n.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)},function(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStoragePendingEventsDispatcher=t.PendingEventsDispatcher=void 0;var o=y.getLogger("EventProcessor"),a=function(){function e(e){var t=e.eventDispatcher,r=e.store;this.dispatcher=t,this.store=r}return e.prototype.dispatchEvent=function(e,t){this.send({uuid:b.generateUUID(),timestamp:b.getTimestamp(),request:e},t)},e.prototype.sendPendingEvents=function(){var e=this,t=this.store.values();o.debug("Sending %s pending events from previous page",t.length),t.forEach((function(t){try{e.send(t,(function(){}))}catch(e){}}))},e.prototype.send=function(e,t){var r=this;this.store.set(e.uuid,e),this.dispatcher.dispatchEvent(e.request,(function(n){r.store.remove(e.uuid),t(n)}))},e}();t.PendingEventsDispatcher=a;var s=function(e){function t(t){var r=t.eventDispatcher;return e.call(this,{eventDispatcher:r,store:new G.LocalStorageStore({maxValues:100,key:"fs_optly_pending_events"})})||this}return i(t,e),t}(a);t.LocalStoragePendingEventsDispatcher=s}));i(K);K.LocalStoragePendingEventsDispatcher,K.PendingEventsDispatcher;var j=o((function(e,t){var r=n&&n.__assign||function(){return(r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.formatEvents=t.buildConversionEventV1=t.buildImpressionEventV1=t.makeBatchedEventV1=void 0;function i(e){var t=[],r=e[0];return e.forEach((function(e){if("conversion"===e.type||"impression"===e.type){var r=s(e);"impression"===e.type?r.snapshots.push(a(e)):"conversion"===e.type&&r.snapshots.push(o(e)),t.push(r)}})),{client_name:r.context.clientName,client_version:r.context.clientVersion,account_id:r.context.accountId,project_id:r.context.projectId,revision:r.context.revision,anonymize_ip:r.context.anonymizeIP,enrich_decisions:!0,visitors:t}}function o(e){var t=r({},e.tags);delete t.revenue,delete t.value;var n={entity_id:e.event.id,key:e.event.key,timestamp:e.timestamp,uuid:e.uuid};return e.tags&&(n.tags=e.tags),null!=e.value&&(n.value=e.value),null!=e.revenue&&(n.revenue=e.revenue),{events:[n]}}function a(e){var t=e.layer,r=e.experiment,n=e.variation,i=e.ruleKey,o=e.flagKey,a=e.ruleType,s=t?t.id:null;return{decisions:[{campaign_id:s,experiment_id:r?r.id:null,variation_id:n?n.id:null,metadata:{flag_key:o,rule_key:i,rule_type:a,variation_key:n?n.key:""}}],events:[{entity_id:s,timestamp:e.timestamp,key:"campaign_activated",uuid:e.uuid}]}}function s(e){var t={snapshots:[],visitor_id:e.user.id,attributes:[]};return e.user.attributes.forEach((function(e){t.attributes.push({entity_id:e.entityId,key:e.key,type:"custom",value:e.value})})),"boolean"==typeof e.context.botFiltering&&t.attributes.push({entity_id:"$opt_bot_filtering",key:"$opt_bot_filtering",type:"custom",value:e.context.botFiltering}),t}t.makeBatchedEventV1=i,t.buildImpressionEventV1=function(e){var t=s(e);return t.snapshots.push(a(e)),{client_name:e.context.clientName,client_version:e.context.clientVersion,account_id:e.context.accountId,project_id:e.context.projectId,revision:e.context.revision,anonymize_ip:e.context.anonymizeIP,enrich_decisions:!0,visitors:[t]}},t.buildConversionEventV1=function(e){var t=s(e);return t.snapshots.push(o(e)),{client_name:e.context.clientName,client_version:e.context.clientVersion,account_id:e.context.accountId,project_id:e.context.projectId,revision:e.context.revision,anonymize_ip:e.context.anonymizeIP,enrich_decisions:!0,visitors:[t]}},t.formatEvents=function(e){return{url:"https://logx.optimizely.com/v1/events",httpVerb:"POST",params:i(e)}}}));i(j);j.formatEvents,j.buildConversionEventV1,j.buildImpressionEventV1,j.makeBatchedEventV1;var H=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.reqsInFlightCount=0,this.reqsCompleteResolvers=[]}return e.prototype.trackRequest=function(e){var t=this;this.reqsInFlightCount++;var r=function(){t.reqsInFlightCount--,0===t.reqsInFlightCount&&(t.reqsCompleteResolvers.forEach((function(e){return e()})),t.reqsCompleteResolvers=[])};e.then(r,r)},e.prototype.onRequestsComplete=function(){var e=this;return new Promise((function(t){0===e.reqsInFlightCount?t():e.reqsCompleteResolvers.push(t)}))},e}();t.default=r}));i(H);var Y=o((function(e,t){var r=n&&n.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{u(n.next(e))}catch(e){o(e)}}function s(e){try{u(n.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}u((n=n.apply(e,t||[])).next())}))},i=n&&n.__generator||function(e,t){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}},o=n&&n.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogTierV1EventProcessor=void 0;var a=o(H),s=y.getLogger("LogTierV1EventProcessor"),u=function(){function e(e){var t=e.dispatcher,r=e.flushInterval,n=void 0===r?x.DEFAULT_FLUSH_INTERVAL:r,i=e.batchSize,o=void 0===i?x.DEFAULT_BATCH_SIZE:i,s=e.notificationCenter;this.dispatcher=t,this.notificationCenter=s,this.requestTracker=new a.default,n=x.validateAndGetFlushInterval(n),o=x.validateAndGetBatchSize(o),this.queue=x.getQueue(o,n,this.drainQueue.bind(this),D.areEventContextsEqual)}return e.prototype.drainQueue=function(e){var t=this,r=new Promise((function(r){if(s.debug("draining queue with %s events",e.length),0!==e.length){var n=j.formatEvents(e);t.dispatcher.dispatchEvent(n,(function(){r()})),x.sendEventNotification(t.notificationCenter,n)}else r()}));return this.requestTracker.trackRequest(r),r},e.prototype.process=function(e){this.queue.enqueue(e)},e.prototype.stop=function(){try{return this.queue.stop(),this.requestTracker.onRequestsComplete()}catch(e){s.error('Error stopping EventProcessor: "%s"',e.message,e)}return Promise.resolve()},e.prototype.start=function(){return r(this,void 0,void 0,(function(){return i(this,(function(e){return this.queue.start(),[2]}))}))},e}();t.LogTierV1EventProcessor=u}));i(Y);Y.LogTierV1EventProcessor;var X=o((function(e,t){var r=n&&n.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=n&&n.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(D,t),i(x,t),i(B,t),i(w,t),i(K,t),i(j,t),i(Y,t)}));i(X);var q=X.LogTierV1EventProcessor,z=X.LocalStoragePendingEventsDispatcher,J={NOTSET:0,DEBUG:1,INFO:2,WARNING:3,ERROR:4},W={CONDITION_EVALUATOR_ERROR:"%s: Error evaluating audience condition of type %s: %s",DATAFILE_AND_SDK_KEY_MISSING:"%s: You must provide at least one of sdkKey or datafile. Cannot start Optimizely",EXPERIMENT_KEY_NOT_IN_DATAFILE:"%s: Experiment key %s is not in datafile.",FEATURE_NOT_IN_DATAFILE:"%s: Feature key %s is not in datafile.",IMPROPERLY_FORMATTED_EXPERIMENT:"%s: Experiment key %s is improperly formatted.",INVALID_ATTRIBUTES:"%s: Provided attributes are in an invalid format.",INVALID_BUCKETING_ID:"%s: Unable to generate hash for bucketing ID %s: %s",INVALID_DATAFILE:"%s: Datafile is invalid - property %s: %s",INVALID_DATAFILE_MALFORMED:"%s: Datafile is invalid because it is malformed.",INVALID_CONFIG:"%s: Provided Optimizely config is in an invalid format.",INVALID_JSON:"%s: JSON object is not valid.",INVALID_ERROR_HANDLER:'%s: Provided "errorHandler" is in an invalid format.',INVALID_EVENT_DISPATCHER:'%s: Provided "eventDispatcher" is in an invalid format.',INVALID_EVENT_TAGS:"%s: Provided event tags are in an invalid format.",INVALID_EXPERIMENT_KEY:"%s: Experiment key %s is not in datafile. It is either invalid, paused, or archived.",INVALID_EXPERIMENT_ID:"%s: Experiment ID %s is not in datafile.",INVALID_GROUP_ID:"%s: Group ID %s is not in datafile.",INVALID_LOGGER:'%s: Provided "logger" is in an invalid format.',INVALID_ROLLOUT_ID:"%s: Invalid rollout ID %s attached to feature %s",INVALID_USER_ID:"%s: Provided user ID is in an invalid format.",INVALID_USER_PROFILE_SERVICE:"%s: Provided user profile service instance is in an invalid format: %s.",NO_DATAFILE_SPECIFIED:"%s: No datafile specified. Cannot start optimizely.",NO_JSON_PROVIDED:"%s: No JSON object to validate against schema.",NO_VARIATION_FOR_EXPERIMENT_KEY:"%s: No variation key %s defined in datafile for experiment %s.",UNDEFINED_ATTRIBUTE:"%s: Provided attribute: %s has an undefined value.",UNRECOGNIZED_ATTRIBUTE:"%s: Unrecognized attribute %s provided. Pruning before sending event to Optimizely.",UNABLE_TO_CAST_VALUE:"%s: Unable to cast value %s to type %s, returning null.",USER_NOT_IN_FORCED_VARIATION:"%s: User %s is not in the forced variation map. Cannot remove their forced variation.",USER_PROFILE_LOOKUP_ERROR:'%s: Error while looking up user profile for user ID "%s": %s.',USER_PROFILE_SAVE_ERROR:'%s: Error while saving user profile for user ID "%s": %s.',VARIABLE_KEY_NOT_IN_DATAFILE:'%s: Variable with key "%s" associated with feature with key "%s" is not in datafile.',VARIATION_ID_NOT_IN_DATAFILE:"%s: No variation ID %s defined in datafile for experiment %s.",VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT:"%s: Variation ID %s is not in the datafile.",INVALID_INPUT_FORMAT:"%s: Provided %s is in an invalid format.",INVALID_DATAFILE_VERSION:"%s: This version of the JavaScript SDK does not support the given datafile version: %s",INVALID_VARIATION_KEY:"%s: Provided variation key is in an invalid format."},Z={ACTIVATE_USER:"%s: Activating user %s in experiment %s.",DISPATCH_CONVERSION_EVENT:"%s: Dispatching conversion event to URL %s with params %s.",DISPATCH_IMPRESSION_EVENT:"%s: Dispatching impression event to URL %s with params %s.",DEPRECATED_EVENT_VALUE:"%s: Event value is deprecated in %s call.",EVENT_KEY_NOT_FOUND:"%s: Event key %s is not in datafile.",EXPERIMENT_NOT_RUNNING:"%s: Experiment %s is not running.",FEATURE_ENABLED_FOR_USER:"%s: Feature %s is enabled for user %s.",FEATURE_NOT_ENABLED_FOR_USER:"%s: Feature %s is not enabled for user %s.",FEATURE_HAS_NO_EXPERIMENTS:"%s: Feature %s is not attached to any experiments.",FAILED_TO_PARSE_VALUE:'%s: Failed to parse event value "%s" from event tags.',FAILED_TO_PARSE_REVENUE:'%s: Failed to parse revenue value "%s" from event tags.',FORCED_BUCKETING_FAILED:"%s: Variation key %s is not in datafile. Not activating user %s.",INVALID_OBJECT:"%s: Optimizely object is not valid. Failing %s.",INVALID_CLIENT_ENGINE:"%s: Invalid client engine passed: %s. Defaulting to node-sdk.",INVALID_VARIATION_ID:"%s: Bucketed into an invalid variation ID. Returning null.",NOTIFICATION_LISTENER_EXCEPTION:"%s: Notification listener for (%s) threw exception: %s",NO_ROLLOUT_EXISTS:"%s: There is no rollout of feature %s.",NOT_ACTIVATING_USER:"%s: Not activating user %s for experiment %s.",NOT_TRACKING_USER:"%s: Not tracking user %s.",PARSED_REVENUE_VALUE:'%s: Parsed revenue value "%s" from event tags.',PARSED_NUMERIC_VALUE:'%s: Parsed event value "%s" from event tags.',RETURNING_STORED_VARIATION:'%s: Returning previously activated variation "%s" of experiment "%s" for user "%s" from user profile.',ROLLOUT_HAS_NO_EXPERIMENTS:"%s: Rollout of feature %s has no experiments",SAVED_VARIATION:'%s: Saved variation "%s" of experiment "%s" for user "%s".',SAVED_VARIATION_NOT_FOUND:"%s: User %s was previously bucketed into variation with ID %s for experiment %s, but no matching variation was found.",SHOULD_NOT_DISPATCH_ACTIVATE:'%s: Experiment %s is not in "Running" state. Not activating user.',SKIPPING_JSON_VALIDATION:"%s: Skipping JSON schema validation.",TRACK_EVENT:"%s: Tracking event %s for user %s.",USER_ASSIGNED_TO_EXPERIMENT_BUCKET:"%s: Assigned bucket %s to user with bucketing ID %s.",USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP:"%s: User %s is in experiment %s of group %s.",USER_BUCKETED_INTO_TARGETING_RULE:"%s: User %s bucketed into targeting rule %s.",USER_IN_FEATURE_EXPERIMENT:"%s: User %s is in variation %s of experiment %s on the feature %s.",USER_IN_ROLLOUT:"%s: User %s is in rollout of feature %s.",USER_BUCKETED_INTO_EVERYONE_TARGETING_RULE:"%s: User %s bucketed into everyone targeting rule.",USER_NOT_BUCKETED_INTO_EVERYONE_TARGETING_RULE:"%s: User %s not bucketed into everyone targeting rule due to traffic allocation.",USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP:"%s: User %s is not in experiment %s of group %s.",USER_NOT_BUCKETED_INTO_ANY_EXPERIMENT_IN_GROUP:"%s: User %s is not in any experiment of group %s.",USER_NOT_BUCKETED_INTO_TARGETING_RULE:"%s User %s not bucketed into targeting rule %s due to traffic allocation. Trying everyone rule.",USER_NOT_IN_FEATURE_EXPERIMENT:"%s: User %s is not in any experiment on the feature %s.",USER_NOT_IN_ROLLOUT:"%s: User %s is not in rollout of feature %s.",USER_FORCED_IN_VARIATION:"%s: User %s is forced in variation %s.",USER_MAPPED_TO_FORCED_VARIATION:"%s: Set variation %s for experiment %s and user %s in the forced variation map.",USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE:"%s: User %s does not meet conditions for targeting rule %s.",USER_MEETS_CONDITIONS_FOR_TARGETING_RULE:"%s: User %s meets conditions for targeting rule %s.",USER_HAS_VARIATION:"%s: User %s is in variation %s of experiment %s.",USER_HAS_FORCED_VARIATION:"%s: Variation %s is mapped to experiment %s and user %s in the forced variation map.",USER_HAS_NO_VARIATION:"%s: User %s is in no variation of experiment %s.",USER_HAS_NO_FORCED_VARIATION:"%s: User %s is not in the forced variation map.",USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT:"%s: No experiment %s mapped to user %s in the forced variation map.",USER_NOT_IN_ANY_EXPERIMENT:"%s: User %s is not in any experiment of group %s.",USER_NOT_IN_EXPERIMENT:"%s: User %s does not meet conditions to be in experiment %s.",USER_RECEIVED_DEFAULT_VARIABLE_VALUE:'%s: User "%s" is not in any variation or rollout rule. Returning default value for variable "%s" of feature flag "%s".',FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE:'%s: Feature "%s" is not enabled for user %s. Returning the default variable value "%s".',VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE:'%s: Variable "%s" is not used in variation "%s". Returning default value.',USER_RECEIVED_VARIABLE_VALUE:'%s: Got variable value "%s" for variable "%s" of feature flag "%s"',VALID_DATAFILE:"%s: Datafile is valid.",VALID_USER_PROFILE_SERVICE:"%s: Valid user profile service provided.",VARIATION_REMOVED_FOR_USER:"%s: Variation mapped to experiment %s has been removed for user %s.",VARIABLE_REQUESTED_WITH_WRONG_TYPE:'%s: Requested variable type "%s", but variable is of type "%s". Use correct API to retrieve value. Returning None.',VALID_BUCKETING_ID:'%s: BucketingId is valid: "%s"',BUCKETING_ID_NOT_STRING:"%s: BucketingID attribute is not a string. Defaulted to userId",EVALUATING_AUDIENCE:'%s: Starting to evaluate audience "%s" with conditions: %s.',EVALUATING_AUDIENCES_COMBINED:'%s: Evaluating audiences for %s "%s": %s.',AUDIENCE_EVALUATION_RESULT:'%s: Audience "%s" evaluated to %s.',AUDIENCE_EVALUATION_RESULT_COMBINED:"%s: Audiences for %s %s collectively evaluated to %s.",MISSING_ATTRIBUTE_VALUE:'%s: Audience condition %s evaluated to UNKNOWN because no value was passed for user attribute "%s".',UNEXPECTED_CONDITION_VALUE:"%s: Audience condition %s evaluated to UNKNOWN because the condition value is not supported.",UNEXPECTED_TYPE:'%s: Audience condition %s evaluated to UNKNOWN because a value of type "%s" was passed for user attribute "%s".',UNEXPECTED_TYPE_NULL:'%s: Audience condition %s evaluated to UNKNOWN because a null value was passed for user attribute "%s".',UNKNOWN_CONDITION_TYPE:"%s: Audience condition %s has an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.",UNKNOWN_MATCH_TYPE:"%s: Audience condition %s uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK.",UPDATED_OPTIMIZELY_CONFIG:"%s: Updated Optimizely config to revision %s (project id %s)",OUT_OF_BOUNDS:'%s: Audience condition %s evaluated to UNKNOWN because the number value for user attribute "%s" is not in the range [-2^53, +2^53].',UNABLE_TO_ATTACH_UNLOAD:'%s: unable to bind optimizely.close() to page unload event: "%s"'},Q={REVENUE:"revenue",VALUE:"value"},$={BOT_FILTERING:"$opt_bot_filtering",BUCKETING_ID:"$opt_bucketing_id",STICKY_BUCKETING_KEY:"$opt_experiment_bucket_map",USER_AGENT:"$opt_user_agent"},ee=["node-sdk","react-sdk","javascript-sdk"],te=k,re={AB_TEST:"ab-test",FEATURE:"feature",FEATURE_TEST:"feature-test",FEATURE_VARIABLE:"feature-variable",ALL_FEATURE_VARIABLES:"all-feature-variables"},ne={FEATURE_TEST:"feature-test",ROLLOUT:"rollout",EXPERIMENT:"experiment"},ie={RULE:"rule",EXPERIMENT:"experiment"},oe={BOOLEAN:"boolean",DOUBLE:"double",INTEGER:"integer",STRING:"string",JSON:"json"},ae={V2:"2",V3:"3",V4:"4"},se=Object.freeze({__proto__:null,LOG_LEVEL:J,ERROR_MESSAGES:W,LOG_MESSAGES:Z,RESERVED_EVENT_KEYWORDS:Q,CONTROL_ATTRIBUTES:$,JAVASCRIPT_CLIENT_ENGINE:"javascript-sdk",NODE_CLIENT_ENGINE:"node-sdk",REACT_CLIENT_ENGINE:"react-sdk",NODE_CLIENT_VERSION:"4.4.0",VALID_CLIENT_ENGINES:ee,NOTIFICATION_TYPES:te,DECISION_NOTIFICATION_TYPES:re,DECISION_SOURCES:ne,AUDIENCE_EVALUATION_TYPES:ie,FEATURE_VARIABLE_TYPES:oe,DATAFILE_VERSIONS:ae}),ue="CONFIG_VALIDATOR",le=[ae.V2,ae.V3,ae.V4],ce=function(e){if("object"==typeof e&&null!==e){if(e.errorHandler&&"function"!=typeof e.errorHandler.handleError)throw new Error(F(W.INVALID_ERROR_HANDLER,ue));if(e.eventDispatcher&&"function"!=typeof e.eventDispatcher.dispatchEvent)throw new Error(F(W.INVALID_EVENT_DISPATCHER,ue));if(e.logger&&"function"!=typeof e.logger.log)throw new Error(F(W.INVALID_LOGGER,ue));return!0}throw new Error(F(W.INVALID_CONFIG,ue))},fe=function(e){if(!e)throw new Error(F(W.NO_DATAFILE_SPECIFIED,ue));if("string"==typeof e)try{e=JSON.parse(e)}catch(e){throw new Error(F(W.INVALID_DATAFILE_MALFORMED,ue))}if("object"==typeof e&&!Array.isArray(e)&&null!==e&&-1===le.indexOf(e.version))throw new Error(F(W.INVALID_DATAFILE_VERSION,ue,e.version));return e},Ee={handleError:function(){}},de=function(e){return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&")},_e={dispatchEvent:function(e,t){var r,n=e.url,i=e.params;"POST"===e.httpVerb?((r=new XMLHttpRequest).open("POST",n,!0),r.setRequestHeader("Content-Type","application/json"),r.onreadystatechange=function(){if(4===r.readyState&&t&&"function"==typeof t)try{t({statusCode:r.status})}catch(e){}},r.send(JSON.stringify(i))):(n+="?wxhr=true",i&&(n+="&"+de(i)),(r=new XMLHttpRequest).open("GET",n,!0),r.onreadystatechange=function(){if(4===r.readyState&&t&&"function"==typeof t)try{t()}catch(e){}},r.send())}};function ge(){}ge.prototype.log=function(){};var pe={createLogger:function(e){return new O(e)},createNoOpLogger:function(){return new ge}},ve=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_UPDATE_INTERVAL=3e5,t.MIN_UPDATE_INTERVAL=1e3,t.DEFAULT_URL_TEMPLATE="https://cdn.optimizely.com/datafiles/%s.json",t.DEFAULT_AUTHENTICATED_URL_TEMPLATE="https://config.optimizely.com/datafiles/auth/%s.json",t.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT=[0,8,16,32,64,128,256,512],t.REQUEST_TIMEOUT_MS=6e4}));i(ve);ve.DEFAULT_UPDATE_INTERVAL,ve.MIN_UPDATE_INTERVAL,ve.DEFAULT_URL_TEMPLATE,ve.DEFAULT_AUTHENTICATED_URL_TEMPLATE,ve.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT,ve.REQUEST_TIMEOUT_MS;var Ie=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=y.getLogger("DatafileManager");t.makeGetRequest=function(e,t){var n=new XMLHttpRequest;return{responsePromise:new Promise((function(i,o){n.open("GET",e,!0),function(e,t){Object.keys(e).forEach((function(r){var n=e[r];t.setRequestHeader(r,n)}))}(t,n),n.onreadystatechange=function(){if(4===n.readyState){if(0===n.status)return void o(new Error("Request error"));var e=function(e){var t=e.getAllResponseHeaders();if(null===t)return{};var r=t.split("\r\n"),n={};return r.forEach((function(e){var t=e.indexOf(": ");if(t>-1){var r=e.slice(0,t),i=e.slice(t+2);i.length>0&&(n[r]=i)}})),n}(n),t={statusCode:n.status,body:n.responseText,headers:e};i(t)}},n.timeout=ve.REQUEST_TIMEOUT_MS,n.ontimeout=function(){r.error("Request timed out")},n.send()})),abort:function(){n.abort()}}}}));i(Ie);Ie.makeGetRequest;var he=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.listeners={},this.listenerId=1}return e.prototype.on=function(e,t){var r=this;this.listeners[e]||(this.listeners[e]={});var n=String(this.listenerId);return this.listenerId++,this.listeners[e][n]=t,function(){r.listeners[e]&&delete r.listeners[e][n]}},e.prototype.emit=function(e,t){var r=this.listeners[e];r&&Object.keys(r).forEach((function(e){(0,r[e])(t)}))},e.prototype.removeAllListeners=function(){this.listeners={}},e}();t.default=r}));i(he);var Re=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(){this.errorCount=0}return e.prototype.getDelay=function(){return 0===this.errorCount?0:1e3*ve.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT[Math.min(ve.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT.length-1,this.errorCount)]+Math.round(1e3*Math.random())},e.prototype.countError=function(){this.errorCount<ve.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT.length-1&&this.errorCount++},e.prototype.reset=function(){this.errorCount=0},e}();t.default=r}));i(Re);var Te=o((function(e,t){var r=n&&n.__assign||function(){return(r=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)},i=n&&n.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var o=i(he),a=i(Re),s=y.getLogger("DatafileManager");function u(e){return e>=200&&e<400}var l={get:function(){return Promise.resolve("")},set:function(){return Promise.resolve()},contains:function(){return Promise.resolve(!1)},remove:function(){return Promise.resolve()}},c=function(){function e(e){var t=this,n=r({},this.getConfigDefaults(),e),i=n.datafile,u=n.autoUpdate,c=void 0!==u&&u,f=n.sdkKey,E=n.updateInterval,d=void 0===E?ve.DEFAULT_UPDATE_INTERVAL:E,_=n.urlTemplate,g=void 0===_?ve.DEFAULT_URL_TEMPLATE:_,p=n.cache,v=void 0===p?l:p;this.cache=v,this.cacheKey="opt-datafile-"+f,this.isReadyPromiseSettled=!1,this.readyPromiseResolver=function(){},this.readyPromiseRejecter=function(){},this.readyPromise=new Promise((function(e,r){t.readyPromiseResolver=e,t.readyPromiseRejecter=r})),i?(this.currentDatafile=i,f||this.resolveReadyPromise()):this.currentDatafile="",this.isStarted=!1,this.datafileUrl=b.sprintf(g,f),this.emitter=new o.default,this.autoUpdate=c,!function(e){return e>=ve.MIN_UPDATE_INTERVAL}(d)?(s.warn("Invalid updateInterval %s, defaulting to %s",d,ve.DEFAULT_UPDATE_INTERVAL),this.updateInterval=ve.DEFAULT_UPDATE_INTERVAL):this.updateInterval=d,this.currentTimeout=null,this.currentRequest=null,this.backoffController=new a.default,this.syncOnCurrentRequestComplete=!1}return e.prototype.get=function(){return this.currentDatafile},e.prototype.start=function(){this.isStarted||(s.debug("Datafile manager started"),this.isStarted=!0,this.backoffController.reset(),this.setDatafileFromCacheIfAvailable(),this.syncDatafile())},e.prototype.stop=function(){return s.debug("Datafile manager stopped"),this.isStarted=!1,this.currentTimeout&&(clearTimeout(this.currentTimeout),this.currentTimeout=null),this.emitter.removeAllListeners(),this.currentRequest&&(this.currentRequest.abort(),this.currentRequest=null),Promise.resolve()},e.prototype.onReady=function(){return this.readyPromise},e.prototype.on=function(e,t){return this.emitter.on(e,t)},e.prototype.onRequestRejected=function(e){this.isStarted&&(this.backoffController.countError(),e instanceof Error?s.error("Error fetching datafile: %s",e.message,e):"string"==typeof e?s.error("Error fetching datafile: %s",e):s.error("Error fetching datafile"))},e.prototype.onRequestResolved=function(e){if(this.isStarted){void 0!==e.statusCode&&u(e.statusCode)?this.backoffController.reset():this.backoffController.countError(),this.trySavingLastModified(e.headers);var t=this.getNextDatafileFromResponse(e);if(""!==t)if(s.info("Updating datafile from response"),this.currentDatafile=t,this.cache.set(this.cacheKey,t),this.isReadyPromiseSettled){var r={datafile:t};this.emitter.emit("update",r)}else this.resolveReadyPromise()}},e.prototype.onRequestComplete=function(){this.isStarted&&(this.currentRequest=null,this.isReadyPromiseSettled||this.autoUpdate||this.rejectReadyPromise(new Error("Failed to become ready")),this.autoUpdate&&this.syncOnCurrentRequestComplete&&this.syncDatafile(),this.syncOnCurrentRequestComplete=!1)},e.prototype.syncDatafile=function(){var e=this,t={};this.lastResponseLastModified&&(t["if-modified-since"]=this.lastResponseLastModified),s.debug("Making datafile request to url %s with headers: %s",this.datafileUrl,(function(){return JSON.stringify(t)})),this.currentRequest=this.makeGetRequest(this.datafileUrl,t);var r=function(){e.onRequestComplete()};this.currentRequest.responsePromise.then((function(t){e.onRequestResolved(t)}),(function(t){e.onRequestRejected(t)})).then(r,r),this.autoUpdate&&this.scheduleNextUpdate()},e.prototype.resolveReadyPromise=function(){this.readyPromiseResolver(),this.isReadyPromiseSettled=!0},e.prototype.rejectReadyPromise=function(e){this.readyPromiseRejecter(e),this.isReadyPromiseSettled=!0},e.prototype.scheduleNextUpdate=function(){var e=this,t=this.backoffController.getDelay(),r=Math.max(t,this.updateInterval);s.debug("Scheduling sync in %s ms",r),this.currentTimeout=setTimeout((function(){e.currentRequest?e.syncOnCurrentRequestComplete=!0:e.syncDatafile()}),r)},e.prototype.getNextDatafileFromResponse=function(e){return s.debug("Response status code: %s",e.statusCode),void 0===e.statusCode||304===e.statusCode?"":u(e.statusCode)?e.body:""},e.prototype.trySavingLastModified=function(e){var t=e["last-modified"]||e["Last-Modified"];void 0!==t&&(this.lastResponseLastModified=t,s.debug("Saved last modified header value from response: %s",this.lastResponseLastModified))},e.prototype.setDatafileFromCacheIfAvailable=function(){var e=this;this.cache.get(this.cacheKey).then((function(t){e.isStarted&&!e.isReadyPromiseSettled&&""!==t&&(s.debug("Using datafile from cache"),e.currentDatafile=t,e.resolveReadyPromise())}))},e}();t.default=c}));i(Te);var ye=o((function(e,t){var r,i=n&&n.__extends||(r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)},function(e,t){function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),o=n&&n.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var a=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return i(t,e),t.prototype.makeGetRequest=function(e,t){return Ie.makeGetRequest(e,t)},t.prototype.getConfigDefaults=function(){return{autoUpdate:!1}},t}(o(Te).default);t.default=a}));i(ye);var Oe=o((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.HttpPollingDatafileManager=ye.default}));i(Oe);var Ne=Oe.HttpPollingDatafileManager,Ae=Math.pow(2,53);var me={assign:function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(!e)return{};if("function"==typeof Object.assign)return Object.assign.apply(Object,r([e],t));for(var i=Object(e),o=0;o<t.length;o++){var a=t[o];if(null!=a)for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(i[s]=a[s])}return i},currentTimestamp:function(){return Math.round((new Date).getTime())},isSafeInteger:function(e){return"number"==typeof e&&Math.abs(e)<=Ae},keyBy:function(e,t){return e?M(e,(function(e){return e[t]})):{}},uuid:C,isNumber:function(e){return"number"==typeof e}},Le="PROJECT_CONFIG";var Ue=function(e,t){void 0===t&&(t=null);var r,n,i=(r=e,(n=me.assign({},r)).audiences=(r.audiences||[]).map((function(e){return me.assign({},e)})),n.experiments=(r.experiments||[]).map((function(e){return me.assign({},e)})),n.featureFlags=(r.featureFlags||[]).map((function(e){return me.assign({},e)})),n.groups=(r.groups||[]).map((function(e){var t=me.assign({},e);return t.experiments=(e.experiments||[]).map((function(e){return me.assign({},e)})),t})),n.rollouts=(r.rollouts||[]).map((function(e){var t=me.assign({},e);return t.experiments=(e.experiments||[]).map((function(e){return me.assign({},e)})),t})),n);return i.__datafileStr=null===t?JSON.stringify(e):t,(i.audiences||[]).forEach((function(e){e.conditions=JSON.parse(e.conditions)})),i.audiencesById=me.keyBy(i.audiences,"id"),me.assign(i.audiencesById,me.keyBy(i.typedAudiences,"id")),i.attributeKeyMap=me.keyBy(i.attributes,"key"),i.eventKeyMap=me.keyBy(i.events,"key"),i.groupIdMap=me.keyBy(i.groups,"id"),Object.keys(i.groupIdMap||{}).forEach((function(e){(i.groupIdMap[e].experiments||[]).forEach((function(t){i.experiments.push(me.assign(t,{groupId:e}))}))})),i.rolloutIdMap=me.keyBy(i.rollouts||[],"id"),P(i.rolloutIdMap||{}).forEach((function(e){(e.experiments||[]).forEach((function(e){i.experiments.push(e),e.variationKeyMap=me.keyBy(e.variations,"key")}))})),i.experimentKeyMap=me.keyBy(i.experiments,"key"),i.experimentIdMap=me.keyBy(i.experiments,"id"),i.variationIdMap={},i.variationVariableUsageMap={},(i.experiments||[]).forEach((function(e){e.variationKeyMap=me.keyBy(e.variations,"key"),me.assign(i.variationIdMap,me.keyBy(e.variations,"id")),P(e.variationKeyMap||{}).forEach((function(e){e.variables&&(i.variationVariableUsageMap[e.id]=me.keyBy(e.variables,"id"))}))})),i.experimentFeatureMap={},i.featureKeyMap=me.keyBy(i.featureFlags||[],"key"),P(i.featureKeyMap||{}).forEach((function(e){e.variables.forEach((function(e){e.type===oe.STRING&&e.subType===oe.JSON&&(e.type=oe.JSON,delete e.subType)})),e.variableKeyMap=me.keyBy(e.variables,"key"),(e.experimentIds||[]).forEach((function(t){i.experimentFeatureMap[t]?i.experimentFeatureMap[t].push(e.id):i.experimentFeatureMap[t]=[e.id];var r=i.experimentIdMap[t];r.groupId&&!e.groupId&&(e.groupId=r.groupId)}))})),i},Se=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(F(W.INVALID_EXPERIMENT_KEY,Le,t));return r.id},De=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(F(W.INVALID_EXPERIMENT_KEY,Le,t));return r.status},Ve=function(e,t){return"Running"===De(e,t)},be=function(e,t,r){var n=e.experimentKeyMap[t];return n.variationKeyMap.hasOwnProperty(r)?n.variationKeyMap[r].id:null},Ce=function(e,t){if(e.experimentKeyMap.hasOwnProperty(t)){var r=e.experimentKeyMap[t];if(r)return r}throw new Error(F(W.EXPERIMENT_KEY_NOT_IN_DATAFILE,Le,t))},Pe=function(e,t,r){if(e.featureKeyMap.hasOwnProperty(t)){var n=e.featureKeyMap[t];if(n)return n}return r.log(J.ERROR,F(W.FEATURE_NOT_IN_DATAFILE,Le,t)),null},Me=function(e,t,r,n){var i=e.featureKeyMap[t];if(!i)return n.log(J.ERROR,F(W.FEATURE_NOT_IN_DATAFILE,Le,t)),null;var o=i.variableKeyMap[r];return o||(n.log(J.ERROR,F(W.VARIABLE_KEY_NOT_IN_DATAFILE,Le,r,t)),null)},Fe=function(e,t,r,n){if(!t||!r)return null;if(!e.variationVariableUsageMap.hasOwnProperty(r.id))return n.log(J.ERROR,F(W.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT,Le,r.id)),null;var i=e.variationVariableUsageMap[r.id][t.id];return i?i.value:null},ke=function(e,t,r){var n;switch(t){case oe.BOOLEAN:"true"!==e&&"false"!==e?(r.log(J.ERROR,F(W.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null):n="true"===e;break;case oe.INTEGER:n=parseInt(e,10),isNaN(n)&&(r.log(J.ERROR,F(W.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null);break;case oe.DOUBLE:n=parseFloat(e),isNaN(n)&&(r.log(J.ERROR,F(W.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null);break;case oe.JSON:try{n=JSON.parse(e)}catch(i){r.log(J.ERROR,F(W.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null}break;default:n=e}return n},xe=function(e,t){return e.eventKeyMap.hasOwnProperty(t)},Be=function(e,t){return e.experimentFeatureMap.hasOwnProperty(t)},we=function(e){return!!e.sendFlagDecisions},Ge=Se,Ke=function(e,t){var r=e.experimentIdMap[t];if(!r)throw new Error(F(W.INVALID_EXPERIMENT_ID,Le,t));return r.layerId},je=function(e,t,r){var n=e.attributeKeyMap[t],i=0===t.indexOf("$opt_");return n?(i&&r.log(J.WARN,F("Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.",t,"$opt_")),n.id):i?t:(r.log(J.DEBUG,F(W.UNRECOGNIZED_ATTRIBUTE,Le,t)),null)},He=function(e,t){var r=e.eventKeyMap[t];return r?r.id:null},Ye=function(e,t){return"Running"===De(e,t)},Xe=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(F(W.INVALID_EXPERIMENT_KEY,Le,t));return r.audienceConditions||r.audienceIds},qe=function(e,t){return e.variationIdMap.hasOwnProperty(t)?e.variationIdMap[t].key:null},ze=be,Je=Ce,We=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(F(W.INVALID_EXPERIMENT_KEY,Le,t));return r.trafficAllocation},Ze=function(e,t,r){if(e.experimentIdMap.hasOwnProperty(t)){var n=e.experimentIdMap[t];if(n)return n}return r.log(J.ERROR,F(W.INVALID_EXPERIMENT_ID,Le,t)),null},Qe=function(e){return e.audiencesById},$e=function(e){return e.__datafileStr},et=function(e){var t;try{t=fe(e.datafile)}catch(e){return{configObj:null,error:e}}if(e.jsonSchemaValidator)try{e.jsonSchemaValidator.validate(t),e.logger.log(J.INFO,F(Z.VALID_DATAFILE,Le))}catch(e){return{configObj:null,error:e}}else e.logger.log(J.INFO,F(Z.SKIPPING_JSON_VALIDATION,Le));var r=[t];return"string"==typeof e.datafile&&r.push(e.datafile),{configObj:Ue.apply(void 0,r),error:null}};function tt(e,t,r,n){var i=e.experimentFeatureMap[r],o={};if(i){var a=n[i],s=(t.variables||[]).reduce((function(e,t){return e[t.id]={id:t.id,value:t.value},e}),{});o=(a||[]).reduce((function(e,r){var n=s[r.id],i=t.featureEnabled&&n?