UNPKG

@optimizely/optimizely-sdk

Version:
1 lines 90 kB
!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";var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t){return e(t={exports:{}},t.exports),t.exports}var i=n((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}}));r(i);i.NoopErrorHandler,i.setErrorHandler,i.getErrorHandler,i.resetErrorHandler;var o=n((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={}))}));r(o);o.LogLevel;for(var a=n((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}}})),s=[],u=0;u<256;++u)s[u]=(u+256).toString(16).substr(1);var l,c,E=function(e,t){var r=t||0,n=s;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("")},f=0,_=0;var d=function(e,t,r){var n=t&&r||0,i=t||[],o=(e=e||{}).node||l,s=void 0!==e.clockseq?e.clockseq:c;if(null==o||null==s){var u=a();null==o&&(o=l=[1|u[0],u[1],u[2],u[3],u[4],u[5]]),null==s&&(s=c=16383&(u[6]<<8|u[7]))}var d=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:_+1,p=d-f+(g-_)/1e4;if(p<0&&void 0===e.clockseq&&(s=s+1&16383),(p<0||d>f)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");f=d,_=g,c=s;var h=(1e4*(268435455&(d+=122192928e5))+g)%4294967296;i[n++]=h>>>24&255,i[n++]=h>>>16&255,i[n++]=h>>>8&255,i[n++]=255&h;var I=d/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++]=s>>>8|128,i[n++]=255&s;for(var v=0;v<6;++v)i[n+v]=o[v];return t||E(i)};var g=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||a)();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||E(i)},p=g;p.v1=d,p.v4=g;var h=p,I=n((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)}))}}));r(I);I.getTimestamp,I.generateUUID,I.isValidEnum,I.groupBy,I.objectValues,I.find,I.keyBy,I.sprintf;var v=n((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 a=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}(),s=function(){function e(e){void 0===e&&(e={}),this.logLevel=o.LogLevel.NOTSET,void 0!==e.logLevel&&I.isValidEnum(o.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),I.isValidEnum(o.LogLevel,e)&&void 0!==e?this.logLevel=e:this.logLevel=o.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 o.LogLevel.DEBUG:return"DEBUG";case o.LogLevel.INFO:return"INFO ";case o.LogLevel.WARNING:return"WARN ";case o.LogLevel.ERROR:return"ERROR";default:return"NOTSET"}},e.prototype.consoleLog=function(e,t){switch(e){case o.LogLevel.DEBUG:console.log.apply(console,t);break;case o.LogLevel.INFO:console.info.apply(console,t);break;case o.LogLevel.WARNING:console.warn.apply(console,t);break;case o.LogLevel.ERROR:console.error.apply(console,t);break;default:console.log.apply(console,t)}},e}();t.ConsoleLogHandler=s;var u=o.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(o.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(o.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(o.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(o.LogLevel.ERROR,e,t)},e.prototype.format=function(e){return(this.messagePrefix?this.messagePrefix+": ":"")+I.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&&i.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}(),E=new a;t.getLogger=function(e){return E.getLogger(e)},t.setLogHandler=function(e){l=e},t.setLogLevel=function(e){e=n(e),u=I.isValidEnum(o.LogLevel,e)&&void 0!==e?e:o.LogLevel.ERROR},t.getLogLevel=function(){return u},t.resetLogger=function(){E=new a,u=o.LogLevel.NOTSET}}));r(v);v.ConsoleLogHandler,v.getLogger,v.setLogHandler,v.setLogLevel,v.getLogLevel,v.resetLogger;var R=n((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(i),r(o),r(v)}));r(R);var T=R.ConsoleLogHandler,O=R.getLogger,N=R.setLogLevel,y=R.LogLevel,A=R.setLogHandler,m=R.setErrorHandler,L=R.getErrorHandler,U=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!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}}));r(U);U.areEventContextsEqual;var S=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=R.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}));r(S);S.SingleEventQueue,S.DefaultEventQueue;var D=n((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={}))}));r(D);var V=D.generateUUID,b=(D.getTimestamp,D.isValidEnum,D.groupBy,D.objectValues),C=(D.objectEntries,D.find,D.keyBy),P=D.sprintf,M=D.NOTIFICATION_TYPES,F=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_FLUSH_INTERVAL=3e4,t.DEFAULT_BATCH_SIZE=10;var r=R.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 S.DefaultEventQueue({flushInterval:t,maxQueueSize:e,sink:r,batchComparator:n}):new S.SingleEventQueue({sink:r})},t.sendEventNotification=function(e,t){e&&e.sendNotifications(D.NOTIFICATION_TYPES.LOG_EVENT,t)}}));r(F);F.DEFAULT_FLUSH_INTERVAL,F.DEFAULT_BATCH_SIZE,F.validateAndGetFlushInterval,F.validateAndGetBatchSize,F.getQueue,F.sendEventNotification;var k=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=R.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 D.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}));r(k);k.LocalStorageStore;var x=n((function(e,r){var n,i=t&&t.__extends||(n=function(e,t){return(n=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 r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(r,"__esModule",{value:!0});var o=R.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:D.generateUUID(),timestamp:D.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}();r.PendingEventsDispatcher=a;var s=function(e){function t(t){var r=t.eventDispatcher;return e.call(this,{eventDispatcher:r,store:new k.LocalStorageStore({maxValues:100,key:"fs_optly_pending_events"})})||this}return i(t,e),t}(a);r.LocalStoragePendingEventsDispatcher=s}));r(x);x.PendingEventsDispatcher,x.LocalStoragePendingEventsDispatcher;var B=n((function(e,r){var n=t&&t.__assign||function(){return(n=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(r,"__esModule",{value:!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=n({},e.tags);delete t.revenue,delete t.value;var r={entity_id:e.event.id,key:e.event.key,timestamp:e.timestamp,uuid:e.uuid};return e.tags&&(r.tags=e.tags),null!=e.value&&(r.value=e.value),null!=e.revenue&&(r.revenue=e.revenue),{events:[r]}}function a(e){var t=e.layer,r=e.experiment,n=e.variation,i=t?t.id:null;return{decisions:[{campaign_id:i,experiment_id:r?r.id:null,variation_id:n?n.id:null}],events:[{entity_id:i,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}r.makeBatchedEventV1=i,r.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]}},r.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]}},r.formatEvents=function(e){return{url:"https://logx.optimizely.com/v1/events",httpVerb:"POST",params:i(e)}}}));r(B);B.makeBatchedEventV1,B.buildImpressionEventV1,B.buildConversionEventV1,B.formatEvents;var w=n((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}));r(w);var G=n((function(e,r){var n=t&&t.__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){e.done?i(e.value):new r((function(t){t(e.value)})).then(a,s)}u((n=n.apply(e,t||[])).next())}))},i=t&&t.__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=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var a=o(w),s=R.getLogger("LogTierV1EventProcessor"),u=function(){function e(e){var t=e.dispatcher,r=e.flushInterval,n=void 0===r?F.DEFAULT_FLUSH_INTERVAL:r,i=e.batchSize,o=void 0===i?F.DEFAULT_BATCH_SIZE:i,s=e.notificationCenter;this.dispatcher=t,this.notificationCenter=s,this.requestTracker=new a.default,n=F.validateAndGetFlushInterval(n),o=F.validateAndGetBatchSize(o),this.queue=F.getQueue(o,n,this.drainQueue.bind(this),U.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=B.formatEvents(e);t.dispatcher.dispatchEvent(n,(function(){r()})),F.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 n(this,void 0,void 0,(function(){return i(this,(function(e){return this.queue.start(),[2]}))}))},e}();r.LogTierV1EventProcessor=u}));r(G);G.LogTierV1EventProcessor;var K=n((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(U),r(F),r(x),r(B),r(G)}));r(K);var j=K.LogTierV1EventProcessor,H=K.LocalStoragePendingEventsDispatcher,Y=Math.pow(2,53);function X(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(!e)return{};if("function"==typeof Object.assign)return Object.assign.apply(Object,[e].concat(t));for(var n=Object(e),i=0;i<t.length;i++){var o=t[i];if(null!=o)for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(n[a]=o[a])}return n}function q(){return Math.round((new Date).getTime())}function z(e){return"number"==typeof e&&Math.abs(e)<=Y}function J(e,t){return e?C(e,(function(e){return e[t]})):{}}function W(e){return"number"==typeof e}var Z={NOTSET:0,DEBUG:1,INFO:2,WARNING:3,ERROR:4},Q={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."},$={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"'},ee={REVENUE:"revenue",VALUE:"value"},te={BOT_FILTERING:"$opt_bot_filtering",BUCKETING_ID:"$opt_bucketing_id",STICKY_BUCKETING_KEY:"$opt_experiment_bucket_map",USER_AGENT:"$opt_user_agent"},re=["node-sdk","react-sdk","javascript-sdk"],ne=M,ie={AB_TEST:"ab-test",FEATURE:"feature",FEATURE_TEST:"feature-test",FEATURE_VARIABLE:"feature-variable",ALL_FEATURE_VARIABLES:"all-feature-variables"},oe={FEATURE_TEST:"feature-test",ROLLOUT:"rollout"},ae={RULE:"rule",EXPERIMENT:"experiment"},se={BOOLEAN:"boolean",DOUBLE:"double",INTEGER:"integer",STRING:"string",JSON:"json"},ue={V2:"2",V3:"3",V4:"4"},le=Object.freeze({__proto__:null,LOG_LEVEL:Z,ERROR_MESSAGES:Q,LOG_MESSAGES:$,RESERVED_EVENT_KEYWORDS:ee,CONTROL_ATTRIBUTES:te,JAVASCRIPT_CLIENT_ENGINE:"javascript-sdk",NODE_CLIENT_ENGINE:"node-sdk",REACT_CLIENT_ENGINE:"react-sdk",NODE_CLIENT_VERSION:"4.3.4",VALID_CLIENT_ENGINES:re,NOTIFICATION_TYPES:ne,DECISION_NOTIFICATION_TYPES:ie,DECISION_SOURCES:oe,AUDIENCE_EVALUATION_TYPES:ae,FEATURE_VARIABLE_TYPES:se,DATAFILE_VERSIONS:ue}),ce="CONFIG_VALIDATOR",Ee=[ue.V2,ue.V3,ue.V4],fe=function(e){if("object"==typeof e&&null!==e){if(e.errorHandler&&"function"!=typeof e.errorHandler.handleError)throw new Error(P(Q.INVALID_ERROR_HANDLER,ce));if(e.eventDispatcher&&"function"!=typeof e.eventDispatcher.dispatchEvent)throw new Error(P(Q.INVALID_EVENT_DISPATCHER,ce));if(e.logger&&"function"!=typeof e.logger.log)throw new Error(P(Q.INVALID_LOGGER,ce));return!0}throw new Error(P(Q.INVALID_CONFIG,ce))},_e=function(e){if(!e)throw new Error(P(Q.NO_DATAFILE_SPECIFIED,ce));if("string"==typeof e)try{e=JSON.parse(e)}catch(e){throw new Error(P(Q.INVALID_DATAFILE_MALFORMED,ce))}if("object"==typeof e&&!Array.isArray(e)&&null!==e&&-1===Ee.indexOf(e.version))throw new Error(P(Q.INVALID_DATAFILE_VERSION,ce,e.version));return e},de={handleError:function(){}},ge=function(e){return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&")},pe={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+="&"+ge(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 he(){}he.prototype.log=function(){};var Ie={createLogger:function(e){return new T(e)},createNoOpLogger:function(){return new he}},ve=n((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}));r(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 Re=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r=R.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()}}}}));r(Re);Re.makeGetRequest;var Te=n((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}));r(Te);var Oe=n((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}));r(Oe);var Ne=n((function(e,r){var n=t&&t.__assign||function(){return(n=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=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var o=i(Te),a=i(Oe),s=R.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,r=n({},this.getConfigDefaults(),e),i=r.datafile,u=r.autoUpdate,c=void 0!==u&&u,E=r.sdkKey,f=r.updateInterval,_=void 0===f?ve.DEFAULT_UPDATE_INTERVAL:f,d=r.urlTemplate,g=void 0===d?ve.DEFAULT_URL_TEMPLATE:d,p=r.cache,h=void 0===p?l:p;this.cache=h,this.cacheKey="opt-datafile-"+E,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,E||this.resolveReadyPromise()):this.currentDatafile="",this.isStarted=!1,this.datafileUrl=D.sprintf(g,E),this.emitter=new o.default,this.autoUpdate=c,!function(e){return e>=ve.MIN_UPDATE_INTERVAL}(_)?(s.warn("Invalid updateInterval %s, defaulting to %s",_,ve.DEFAULT_UPDATE_INTERVAL),this.updateInterval=ve.DEFAULT_UPDATE_INTERVAL):this.updateInterval=_,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}();r.default=c}));r(Ne);var ye=n((function(e,r){var n,i=t&&t.__extends||(n=function(e,t){return(n=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 r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__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 Re.makeGetRequest(e,t)},t.prototype.getConfigDefaults=function(){return{autoUpdate:!1}},t}(o(Ne).default);r.default=a}));r(ye);var Ae=n((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.HttpPollingDatafileManager=ye.default}));r(Ae);var me=Ae.HttpPollingDatafileManager,Le="PROJECT_CONFIG";var Ue=function(e,t){void 0===t&&(t=null);var r,n,i=((n=X({},r=e)).audiences=(r.audiences||[]).map((function(e){return X({},e)})),n.experiments=(r.experiments||[]).map((function(e){return X({},e)})),n.featureFlags=(r.featureFlags||[]).map((function(e){return X({},e)})),n.groups=(r.groups||[]).map((function(e){var t=X({},e);return t.experiments=(e.experiments||[]).map((function(e){return X({},e)})),t})),n.rollouts=(r.rollouts||[]).map((function(e){var t=X({},e);return t.experiments=(e.experiments||[]).map((function(e){return X({},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=J(i.audiences,"id"),X(i.audiencesById,J(i.typedAudiences,"id")),i.attributeKeyMap=J(i.attributes,"key"),i.eventKeyMap=J(i.events,"key"),i.groupIdMap=J(i.groups,"id"),Object.keys(i.groupIdMap||{}).forEach((function(e){(i.groupIdMap[e].experiments||[]).forEach((function(t){i.experiments.push(X(t,{groupId:e}))}))})),i.rolloutIdMap=J(i.rollouts||[],"id"),b(i.rolloutIdMap||{}).forEach((function(e){(e.experiments||[]).forEach((function(e){i.experiments.push(e),e.variationKeyMap=J(e.variations,"key")}))})),i.experimentKeyMap=J(i.experiments,"key"),i.experimentIdMap=J(i.experiments,"id"),i.variationIdMap={},i.variationVariableUsageMap={},(i.experiments||[]).forEach((function(e){e.variationKeyMap=J(e.variations,"key"),X(i.variationIdMap,J(e.variations,"id")),b(e.variationKeyMap||{}).forEach((function(e){e.variables&&(i.variationVariableUsageMap[e.id]=J(e.variables,"id"))}))})),i.experimentFeatureMap={},i.featureKeyMap=J(i.featureFlags||[],"key"),b(i.featureKeyMap||{}).forEach((function(e){e.variables.forEach((function(e){e.type===se.STRING&&e.subType===se.JSON&&(e.type=se.JSON,delete e.subType)})),e.variableKeyMap=J(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(P(Q.INVALID_EXPERIMENT_KEY,Le,t));return r.id},De=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(P(Q.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,r){if(e.featureKeyMap.hasOwnProperty(t)){var n=e.featureKeyMap[t];if(n)return n}return r.log(Z.ERROR,P(Q.FEATURE_NOT_IN_DATAFILE,Le,t)),null},Pe=function(e,t,r,n){var i=e.featureKeyMap[t];if(!i)return n.log(Z.ERROR,P(Q.FEATURE_NOT_IN_DATAFILE,Le,t)),null;var o=i.variableKeyMap[r];return o||(n.log(Z.ERROR,P(Q.VARIABLE_KEY_NOT_IN_DATAFILE,Le,r,t)),null)},Me=function(e,t,r,n){if(!t||!r)return null;if(!e.variationVariableUsageMap.hasOwnProperty(r.id))return n.log(Z.ERROR,P(Q.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT,Le,r.id)),null;var i=e.variationVariableUsageMap[r.id][t.id];return i?i.value:null},Fe=function(e,t,r){var n;switch(t){case se.BOOLEAN:"true"!==e&&"false"!==e?(r.log(Z.ERROR,P(Q.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null):n="true"===e;break;case se.INTEGER:n=parseInt(e,10),isNaN(n)&&(r.log(Z.ERROR,P(Q.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null);break;case se.DOUBLE:n=parseFloat(e),isNaN(n)&&(r.log(Z.ERROR,P(Q.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null);break;case se.JSON:try{n=JSON.parse(e)}catch(i){r.log(Z.ERROR,P(Q.UNABLE_TO_CAST_VALUE,Le,e,t)),n=null}break;default:n=e}return n},ke=function(e,t){return e.eventKeyMap.hasOwnProperty(t)},xe=function(e,t){return e.experimentFeatureMap.hasOwnProperty(t)},Be=Se,we=function(e,t){var r=e.experimentIdMap[t];if(!r)throw new Error(P(Q.INVALID_EXPERIMENT_ID,Le,t));return r.layerId},Ge=function(e,t,r){var n=e.attributeKeyMap[t],i=0===t.indexOf("$opt_");return n?(i&&r.log(Z.WARN,P("Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.",t,"$opt_")),n.id):i?t:(r.log(Z.DEBUG,P(Q.UNRECOGNIZED_ATTRIBUTE,Le,t)),null)},Ke=function(e,t){var r=e.eventKeyMap[t];return r?r.id:null},je=function(e,t){return"Running"===De(e,t)},He=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(P(Q.INVALID_EXPERIMENT_KEY,Le,t));return r.audienceConditions||r.audienceIds},Ye=function(e,t){return e.variationIdMap.hasOwnProperty(t)?e.variationIdMap[t].key:null},Xe=be,qe=function(e,t){if(e.experimentKeyMap.hasOwnProperty(t)){var r=e.experimentKeyMap[t];if(r)return r}throw new Error(P(Q.EXPERIMENT_KEY_NOT_IN_DATAFILE,Le,t))},ze=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(P(Q.INVALID_EXPERIMENT_KEY,Le,t));return r.trafficAllocation},Je=function(e,t,r){if(e.experimentIdMap.hasOwnProperty(t)){var n=e.experimentIdMap[t];if(n)return n}return r.log(Z.ERROR,P(Q.INVALID_EXPERIMENT_ID,Le,t)),null},We=function(e){return e.audiencesById},Ze=function(e){return e.__datafileStr},Qe=function(e){var t;try{t=_e(e.datafile)}catch(e){return{configObj:null,error:e}}if(e.jsonSchemaValidator)try{e.jsonSchemaValidator.validate(t),e.logger.log(Z.INFO,P($.VALID_DATAFILE,Le))}catch(e){return{configObj:null,error:e}}else e.logger.log(Z.INFO,P($.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 $e(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?n.value:r.defaultValue;return e[r.key]={id:r.id,key:r.key,type:r.type,value:i},e}),{})}return o}function et(e,t){this.experimentsMap=function(e){var t=(e.rollouts||[]).reduce((function(e,t){return t.experiments.forEach((function(t){e[t.id]=!0})),e}),{}),r=(e.featureFlags||[]).reduce((function(e,t){return e[t.id]=t.variables,e}),{});return(e.experiments||[]).reduce((function(n,i){return t[i.id]||(n[i.key]={id:i.id,key:i.key,variationsMap:(i.variations||[]).reduce((function(t,n){return t[n.key]={id:n.id,key:n.key,variablesMap:$e(e,n,i.id,r)},xe(e,i.id)&&(t[n.key].featureEnabled=n.featureEnabled),t}),{})}),n}),{})}(e),this.featuresMap=function(e,t){return(e.featureFlags||[]).reduce((function(r,n){return r[n.key]={id:n.id,key:n.key,experimentsMap:(n.experimentIds||[]).reduce((function(r,n){var i=e.experimentIdMap[n].key;return r[i]=t[i],r}),{}),variablesMap:(n.variables||[]).reduce((function(e,t){return e[t.key]={id:t.id,key:t.key,type:t.type,value:t.defaultValue},e}),{})},r}),{})}(e,this.experimentsMap),this.revision=e.revision,this.__datafile=t}et.prototype.getDatafile=function(){return this.__datafile};var tt={OptimizelyConfig:et},rt=O();function nt(e,t){return e instanceof Error?e.message:t||"Unknown error"}function it(e){try{this.__initialize(e)}catch(e){rt.error(e),this.__updateListeners=[],this.__configObj=null,this.__optimizelyConfigObj=null,this.__readyPromise=Promise.resolve({success:!1,reason:nt(e,"Error in initialize")})}}it.prototype.__initialize=function(e){if(this.__updateListeners=[],this.jsonSchemaValidator=e.jsonSchemaValidator,!e.datafile&&!e.sdkKey){this.__configObj=null;var t=new Error(P(Q.DATAFILE_AND_SDK_KEY_MISSING,"PROJECT_CONFIG_MANAGER"));return this.__readyPromise=Promise.resolve({success:!1,reason:nt(t)}),void rt.error(t)}var r;if(e.datafile?(r=this.__handleNewDatafile(e.datafile))&&(this.__configObj=null):this.__configObj=null,e.sdkKey){var n={sdkKey:e.sdkKey};this.__validateDatafileOptions(e.datafileOptions)&&X(n,e.datafileOptions),this.__configObj&&(n.datafile=Ze(this.__configObj)),this.datafileManager=new me(n),this.datafileManager.start(),this.__readyPromise=this.datafileManager.onReady().then(this.__onDatafileManagerReadyFulfill.bind(this),this.__onDatafileManagerReadyReject.bind(this)),this.datafileManager.on("update",this.__onDatafileManagerUpdate.bind(this))}else this.__configObj?this.__readyPromise=Promise.resolve({success:!0}):this.__readyPromise=Promise.resolve({success:!1,reason:nt(r,"Invalid datafile")})},it.prototype.__onDatafileManagerReadyFulfill=function(){var e=this.__handleNewDatafile(this.datafileManager.get());