@eventvisor/sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- const e={schemaVersion:"1",revision:"0",attributes:{},events:{},destinations:{},effects:{}};function t(e){let r=[];if("string"==typeof e)r.push({storage:e});else if(Array.isArray(e))for(const i of e){const e=t(i);e&&(r=r.concat(e))}else"object"==typeof e&&r.push(e);return r}class r{constructor(e){const{datafile:t,logger:r}=e;this.datafile=t,this.schemaVersion=t.schemaVersion,this.revision=t.revision,this.regexCache={},this.logger=r}getSchemaVersion(){return this.schemaVersion}getRevision(){return this.revision}getAttribute(e){return this.datafile.attributes[e]}getAttributeNames(){return Object.keys(this.datafile.attributes)}getEvent(e){return this.datafile.events[e]}getDestination(e){return this.datafile.destinations[e]}getDestinationNames(){return Object.keys(this.datafile.destinations)}getEffect(e){return this.datafile.effects[e]}getEffectNames(){return Object.keys(this.datafile.effects)}getRegex(e,t){const r=t||"",i=`${e}-${r}`;if(this.regexCache[i])return this.regexCache[i];const n=new RegExp(e,r);return this.regexCache[i]=n,n}getPersists(e){return e&&e.persist?t(e.persist):null}}const i="[Eventvisor]",n=function(e,t,r={}){let n="log";"info"===e?n="info":"warn"===e?n="warn":"error"===e&&(n="error"),console[n](i,t,r)};class s{constructor(e){this.level=e.level||s.defaultLevel,this.handle=e.handler||n}setLevel(e){this.level=e}log(e,t,r){s.allLevels.indexOf(this.level)>=s.allLevels.indexOf(e)&&this.handle(e,t,r)}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}function o(e={}){return new s(e)}s.allLevels=["fatal","error","warn","info","debug"],s.defaultLevel="info";class a{constructor(){this.listeners={}}on(e,t){this.listeners[e]||(this.listeners[e]=[]);const r=this.listeners[e];r.push(t);let i=!0;return function(){if(!i)return;i=!1;const e=r.indexOf(t);-1!==e&&r.splice(e,1)}}trigger(e,t={}){const r=this.listeners[e];r&&r.forEach(function(e){try{e(t)}catch(e){console.error(e)}})}clearAll(){this.listeners={}}}var u=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};function l(e){return u(this,void 0,void 0,function*(){const{persists:t,entityName:r,conditionsChecker:i,payload:n}=e;for(const e of t){if(!e.conditions)return e;if(yield i.allAreMatched(e.conditions,{attributeName:r,effectName:r,payload:n}))return e}})}function c(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,getEntityNames:n,getEntity:s}){const o=n(),a={};for(const n of o){const o=s(n);if(!o)continue;const u=e.getPersists(o);if(!u)continue;const c=yield l({persists:u,entityName:n,conditionsChecker:t,payload:{}});if(!c)continue;const d=yield r.readFromStorage(c.storage,`${i}${n}`);null!=d&&(a[n]=d)}return a})}function d(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,entityName:n,entity:s,value:o}){if(!s)return;const a=e.getPersists(s);if(!a)return;const u=yield l({persists:a,entityName:n,conditionsChecker:t,payload:o});u&&(yield r.writeToStorage(u.storage,`${i}${n}`,o))})}var h=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class f{constructor(e){const{logger:t,getDatafileReader:r,emitter:i,getTransformer:n,getConditionsChecker:s,validator:o,modulesManager:a}=e;this.logger=t,this.getDatafileReader=r,this.emitter=i,this.getTransformer=n,this.getConditionsChecker=s,this.validator=o,this.modulesManager=a,this.attributesMap={}}initialize(){return h(this,void 0,void 0,function*(){yield this.initializeFromStorage()})}initializeFromStorage(){return h(this,void 0,void 0,function*(){const e=this.getDatafileReader(),t=yield c({datafileReader:e,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",getEntityNames:()=>e.getAttributeNames(),getEntity:t=>e.getAttribute(t)});this.attributesMap=t})}setAttribute(e,t){return h(this,void 0,void 0,function*(){const r=this.getDatafileReader(),i=r.getAttribute(e);if(!i)return this.logger.error("Attribute schema not found",{attributeName:e}),null;i.deprecated&&this.logger.warn("Attribute is deprecated",{attributeName:e});const n=yield this.validator.validate(i,t);if(!n.valid)return this.logger.warn("Attribute validation failed",{attributeName:e,errors:n.errors}),null;const s=n.value,o=i.transforms?yield this.getTransformer().applyAll(s,i.transforms,{payload:s,attributeName:e}):s;return this.attributesMap[e]=o,this.emitter.trigger("attribute_set",{attributeName:e}),this.logger.debug("Attribute set",{attributeName:e}),yield d({datafileReader:r,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",entityName:e,entity:i,value:t}),o})}isAttributeSet(e){return void 0!==this.attributesMap[e]}getAttributesMap(){return this.attributesMap}getAttributeValue(e){return this.attributesMap[e]||null}removeAttribute(e){return h(this,void 0,void 0,function*(){const t=this.getDatafileReader();yield function(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,entityName:n,entity:s}){if(!s)return;const o=e.getPersists(s);if(!o)return;const a=yield l({persists:o,entityName:n,conditionsChecker:t,payload:{}});a&&(yield r.removeFromStorage(a.storage,`${i}${n}`))})}({datafileReader:t,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",entityName:e,entity:t.getAttribute(e)}),delete this.attributesMap[e],this.emitter.trigger("attribute_removed",{attributeName:e})})}}var g=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class m{constructor(e){const{logger:t,getDatafileReader:r,getSourceResolver:i}=e;this.logger=t,this.getDatafileReader=r,this.getSourceResolver=i,this.modules=[]}registerModule(e){this.modules.find(t=>t.name===e.name)?this.logger.error(`Module ${e.name} already registered`):this.modules.push(e)}getModule(e){return this.modules.find(t=>t.name===e)}removeModule(e){this.getModule(e)?this.modules=this.modules.filter(t=>t.name!==e):this.logger.error(`Module ${e} not found`)}getModuleDependencies(){return{datafileReader:this.getDatafileReader(),logger:this.logger,sourceResolver:this.getSourceResolver()}}lookup(e){return g(this,void 0,void 0,function*(){const[t,...r]=e.split("."),i=r.join("."),n=this.getModule(t);if(n&&n.lookup)try{return yield n.lookup({key:i},this.getModuleDependencies())}catch(e){return this.logger.error("Error in lookup",{moduleName:t,key:i,error:e}),null}return this.logger.error(`Module "${t}" not found with "lookup" function`),null})}handle(e,t,r,i,n){return g(this,void 0,void 0,function*(){const[s,o]=e.split("."),a=this.getModule(s);if(a&&a.handle)try{return yield a.handle({effectName:t,effect:r,step:i,payload:n},this.getModuleDependencies())}catch(e){return void this.logger.error("Error in handle",{moduleName:s,effectName:t,error:e})}this.logger.error(`Module "${s}" not found with "handle" function`)})}transportExists(e){const[t,r]=e.split("."),i=this.getModule(t);return!(!i||!i.transport)}transport(e,t,r,i,n){return g(this,void 0,void 0,function*(){const[s,o]=e.split("."),a=this.getModule(s);if(a&&a.transport)try{return yield a.transport({destinationName:t,eventName:r,eventLevel:n,payload:i},this.getModuleDependencies())}catch(e){return void this.logger.error("Error in transport",{moduleName:s,destinationName:t,eventName:r,error:e})}this.logger.error(`Module "${s}" not found with "transport" function`)})}readFromStorage(e,t){return g(this,void 0,void 0,function*(){const r=this.getModule(e);if(r&&r.readFromStorage)try{return yield r.readFromStorage({key:t},this.getModuleDependencies())}catch(r){return this.logger.error("Error in readFromStorage",{moduleName:e,key:t,error:r}),null}return this.logger.error(`Module "${e}" not found with "readFromStorage" function`),null})}writeToStorage(e,t,r){return g(this,void 0,void 0,function*(){const i=this.getModule(e);if(i&&i.writeToStorage)try{return yield i.writeToStorage({key:t,value:r},this.getModuleDependencies())}catch(i){return void this.logger.error("Error in writeToStorage",{moduleName:e,key:t,value:r,error:i})}this.logger.error(`Module "${e}" not found with "writeToStorage" function`)})}removeFromStorage(e,t){return g(this,void 0,void 0,function*(){const r=this.getModule(e);if(r&&r.removeFromStorage)try{return yield r.removeFromStorage({key:t},this.getModuleDependencies())}catch(r){return void this.logger.error("Error in removeFromStorage",{moduleName:e,key:t,error:r})}this.logger.error(`Module "${e}" not found with "removeFromStorage" function`)})}}var v=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};function p(e,t){return t.reduce((e,t)=>e[t],e)}class y{constructor(e){const{logger:t,modulesManager:r,attributesManager:i,effectsManager:n}=e;this.logger=t,this.modulesManager=r,this.attributesManager=i,this.effectsManager=n}getPath(e){const t=e.split(".");return{name:t[0],path:t.slice(1),fullKey:e}}getOrigin(e){if("string"==typeof e){const t=e.split(".");return{originType:t[0],name:t[1],path:t.slice(2),fullKey:e}}return"source"in e||"source"in e?this.getOrigin(e.source):"attribute"in e?Object.assign({originType:"attribute"},this.getPath(e.attribute)):"effect"in e?Object.assign({originType:"effect"},this.getPath(e.effect)):"payload"in e?Array.isArray(e.payload)?e.payload.map(e=>Object.assign({originType:"payload"},this.getPath(e))):Object.assign({originType:"payload"},this.getPath(e.payload)):"lookup"in e?Object.assign({originType:"lookup"},this.getPath(e.lookup)):"state"in e?Object.assign({originType:"state"},this.getPath(e.state)):null}resolveByOrigin(e){return v(this,arguments,void 0,function*(e,t={}){if(null===e)return null;if("attributes"===e.originType){const t=e.name?this.attributesManager.getAttributeValue(e.name):this.attributesManager.getAttributesMap();return e.path.length>0?p(t,e.path):t}if("attribute"===e.originType){const t=this.attributesManager.getAttributeValue(e.name);return e.path.length>0?p(t,e.path):t}if("effects"===e.originType){const t=e.name?this.effectsManager.getStateValue(e.name):this.effectsManager.getAllStates();return e.path.length>0?p(t,e.path):t}if("effect"===e.originType){const t=this.effectsManager.getStateValue(e.name);return e.path.length>0?p(t,e.path):t}return"lookup"===e.originType?this.modulesManager.lookup(e.fullKey):void 0!==t[e.originType]?p(t[e.originType],[e.name,...e.path].filter(Boolean)):null})}resolve(e){return v(this,arguments,void 0,function*(e,t={}){const r=this.getOrigin(e);return Array.isArray(r)?Promise.all(r.map(e=>this.resolveByOrigin(e,t))):yield this.resolveByOrigin(r,t)})}}const b=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,A=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(b);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},M=e=>"*"===e||"x"===e||"X"===e,N=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},k=(e,t)=>{if(M(e)||M(t))return 0;const[r,i]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(N(e),N(t));return r>i?1:r<i?-1:0},w=(e,t)=>{for(let r=0;r<Math.max(e.length,t.length);r++){const i=k(e[r]||"0",t[r]||"0");if(0!==i)return i}return 0},x=(e,t)=>{const r=A(e),i=A(t),n=r.pop(),s=i.pop(),o=w(r,i);return 0!==o?o:n&&s?w(n.split("."),s.split(".")):n||s?n?-1:1:0};var S=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class R{constructor(e){this.getRegex=e.getRegex,this.sourceResolver=e.sourceResolver,this.logger=e.logger}isMatched(e,t){return S(this,void 0,void 0,function*(){const{operator:r,value:i,regexFlags:n}=e,s=yield this.sourceResolver.resolve(e,t);if("equals"===r)return s===i;if("notEquals"===r)return s!==i;if("before"===r||"after"===r){const e=s instanceof Date?s:new Date(s),t=i instanceof Date?i:new Date(i);return"before"===r?e<t:e>t}if(!Array.isArray(i)||-1===["string","number"].indexOf(typeof s)&&null!==s)if("string"==typeof s&&"string"==typeof i){const e=s;if("contains"===r)return-1!==e.indexOf(i);if("notContains"===r)return-1===e.indexOf(i);if("startsWith"===r)return e.startsWith(i);if("endsWith"===r)return e.endsWith(i);if("semverEquals"===r)return 0===x(e,i);if("semverNotEquals"===r)return 0!==x(e,i);if("semverGreaterThan"===r)return 1===x(e,i);if("semverGreaterThanOrEquals"===r)return x(e,i)>=0;if("semverLessThan"===r)return-1===x(e,i);if("semverLessThanOrEquals"===r)return x(e,i)<=0;if("matches"===r)return this.getRegex(i,n||"").test(e);if("notMatches"===r)return!this.getRegex(i,n||"").test(e)}else if("number"==typeof s&&"number"==typeof i){if("greaterThan"===r)return s>i;if("greaterThanOrEquals"===r)return s>=i;if("lessThan"===r)return s<i;if("lessThanOrEquals"===r)return s<=i}else{if("exists"===r)return void 0!==s;if("notExists"===r)return void 0===s;if(Array.isArray(s)&&"string"==typeof i){const e=s;if("includes"===r)return e.indexOf(i)>-1;if("notIncludes"===r)return-1===e.indexOf(i)}}else{const e=s;if("in"===r)return-1!==i.indexOf(e);if("notIn"===r)return-1===i.indexOf(e)}return!1})}_allAreMatched(e,t){return S(this,void 0,void 0,function*(){if("string"==typeof e)return"*"===e;if("operator"in e)try{return this.isMatched(e,t)}catch(t){return this.logger.warn(t.message,{error:t,details:{condition:e}}),!1}if("and"in e&&Array.isArray(e.and)){for(const r of e.and)if(!(yield this._allAreMatched(r,t)))return!1;return!0}if("or"in e&&Array.isArray(e.or)){for(const r of e.or)if(yield this._allAreMatched(r,t))return!0;return!1}if("not"in e&&Array.isArray(e.not)){for(const r of e.not)if(yield this._allAreMatched(r,t))return!1;return!0}if(Array.isArray(e)){let r=!0;for(const i of e)if(!(yield this._allAreMatched(i,t))){r=!1;break}return r}return!1})}allAreMatched(e,t){return S(this,void 0,void 0,function*(){const r=this.parseIfStringified(e);return this._allAreMatched(r,t)})}parseIfStringified(e){if("string"!=typeof e)return e;if("*"===e)return e;try{return JSON.parse(e)}catch(t){return this.logger.error("Error parsing conditions",{error:t,details:{conditions:e}}),e}}}function E(e,t){var r;let i,n,s,o,a,u,l,c;for("string"==typeof e&&(r=e,e=(new TextEncoder).encode(r)),i=3&e.length,n=e.length-i,s=t,a=3432918353,u=461845907,c=0;c<n;)l=255&e[c]|(255&e[++c])<<8|(255&e[++c])<<16|(255&e[++c])<<24,++c,l=(65535&l)*a+(((l>>>16)*a&65535)<<16)&4294967295,l=l<<15|l>>>17,l=(65535&l)*u+(((l>>>16)*u&65535)<<16)&4294967295,s^=l,s=s<<13|s>>>19,o=5*(65535&s)+((5*(s>>>16)&65535)<<16)&4294967295,s=27492+(65535&o)+(((o>>>16)+58964&65535)<<16);switch(l=0,i){case 3:l^=(255&e[c+2])<<16;case 2:l^=(255&e[c+1])<<8;case 1:l^=255&e[c],l=(65535&l)*a+(((l>>>16)*a&65535)<<16)&4294967295,l=l<<15|l>>>17,l=(65535&l)*u+(((l>>>16)*u&65535)<<16)&4294967295,s^=l}return s^=e.length,s^=s>>>16,s=2246822507*(65535&s)+((2246822507*(s>>>16)&65535)<<16)&4294967295,s^=s>>>13,s=3266489909*(65535&s)+((3266489909*(s>>>16)&65535)<<16)&4294967295,s^=s>>>16,s>>>0}var C=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};const O=Math.pow(2,32),P=1e5;function T(e){const t=E(e,1)/O;return Math.floor(t*P)}class ${}class D{constructor(e){this.logger=e.logger,this.sourceResolver=e.sourceResolver,this.conditionsChecker=e.conditionsChecker,this.transformer=e.transformer}getBucketKey(e,t){return C(this,void 0,void 0,function*(){let r,i;if("string"==typeof e)r="plain",i=[e];else if(Array.isArray(e))r="and",i=e;else if("object"==typeof e&&"or"in e&&Array.isArray(e.or))r="or",i=e.or;else{if("object"!=typeof e)throw this.logger.error("invalid sampleBy",{sampleBy:e}),new Error("invalid sampleBy");r="and",i=[e]}const n=[];for(const e of i){const i=yield this.sourceResolver.resolve(e,t);void 0!==i&&("plain"===r||"and"===r||0===n.length)&&n.push(String(i))}return n.join(".")})}isSampled(e,t){return C(this,void 0,void 0,function*(){const r=(Array.isArray(e)?e:[e]).find(e=>C(this,void 0,void 0,function*(){return!e.conditions||(yield this.conditionsChecker.allAreMatched(e.conditions,t))}));if(r){const e=yield this.getBucketKey(r.by,t),i=T(e);if(r.percentage&&r.percentage>0&&i<r.percentage)return{isSampled:!1,matchedSample:r,bucketedNumber:i,bucketKey:e};if(r.range&&i<r.range[0]&&i>r.range[1])return{isSampled:!1,matchedSample:r,bucketedNumber:i,bucketKey:e}}return{isSampled:!0}})}}class j{constructor(e){this.logger=e.logger,this.conditionsChecker=e.conditionsChecker,this.sourceResolver=e.sourceResolver}applyAll(e,t){return r=this,i=arguments,s=function*(e,t,r={}){let i=e;for(const n of t){if(n.conditions&&!(yield this.conditionsChecker.allAreMatched(n.conditions,r)))continue;let t=yield this.sourceResolver.resolve(n,r);if(null==t&&n.target&&(t=yield this.sourceResolver.resolve({payload:n.target},void 0===r.payload?Object.assign(Object.assign({},r),{payload:e}):r)),n.target){const e=Array.isArray(n.target)?n.target:[n.target];for(const r of e){if("string"==typeof t&&"trim"===n.type&&(i=j.setValueAtPath(i,r,t.trim())),Array.isArray(t)&&"concat"===n.type){const e=n.separator||" ";i=j.setValueAtPath(i,r,t.join(e))}if("set"===n.type&&(i="value"in n?j.setValueAtPath(i,r,n.value):j.setValueAtPath(i,r,t)),"remove"===n.type&&(i=j.removeValueAt(i,r)),"toInteger"===n.type)i=j.setValueAtPath(i,r,parseInt(String(t)));else if("toDouble"===n.type)i=j.setValueAtPath(i,r,parseFloat(String(t)));else if("toString"===n.type)i=j.setValueAtPath(i,r,String(t)||"");else if("toBoolean"===n.type){const e=String(t).toLowerCase();i=j.setValueAtPath(i,r,-1!==["true","1","checked","yes","on","y"].indexOf(e)||!0===t)}}}else"set"===n.type&&"value"in n&&(i=n.value);if("spread"===n.type)if(n.target){const e=j.getValueAtPath(i,n.target);i=j.setValueAtPath(i,n.target,Object.assign(Object.assign({},e||{}),t||{}))}else i=Object.assign(Object.assign({},i||{}),t||{});if("increment"===n.type){const e="number"==typeof n.value?n.value:1;n.target?i=j.setValueAtPath(i,n.target,Number(t)+e):i+=e}else if("decrement"===n.type){const e="number"==typeof n.value?n.value:1;n.target?i=j.setValueAtPath(i,n.target,Number(t)-e):i-=e}if(n.targetMap){const e=[];if(Array.isArray(n.targetMap))for(const t of n.targetMap)Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})});else Object.entries(n.targetMap).forEach(([t,r])=>{e.push({[t]:r})});for(const t of e)"rename"===n.type&&(i=j.renameValueAt(i,t))}}return i},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{u(s.next(e))}catch(e){t(e)}}function a(e){try{u(s.throw(e))}catch(e){t(e)}}function u(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}u((s=s.apply(r,i||[])).next())});var r,i,n,s}static renameValueAt(e,t){if(!e||"object"!=typeof e)return e;if(!t||"object"!=typeof t)return e;const r=Object.entries(t);if(0===r.length)return e;const[i,n]=r[0];if(!i||!n)return e;const s=j.getValueAtPath(e,i);if(void 0===s)return e;const o=JSON.parse(JSON.stringify(e)),a=i.split(".");let u=o;for(let e=0;e<a.length-1;e++){const t=a[e];if(void 0===u[t])return o;u=u[t]}return delete u[a[a.length-1]],j.setValueAtPath(o,n,s)}static getValueAtPath(e,t){if(!t||"string"!=typeof t)return;const r=t.split(".");let i=e;for(const e of r){if(null==i)return;if("object"!=typeof i||Array.isArray(i)){if(!Array.isArray(i)||!/^\d+$/.test(e))return;i=i[parseInt(e)]}else i=i[e]}return i}static setValueAtPath(e,t,r){if(!t||"string"!=typeof t)return e;if(null==e)return e;const i=JSON.parse(JSON.stringify(e)),n=t.split(".");let s=i;for(let e=0;e<n.length-1;e++){const t=n[e];void 0===s[t]&&(/^\d+$/.test(n[e+1])?s[t]=[]:s[t]={}),s=s[t]}return s[n[n.length-1]]=r,i}static removeValueAt(e,t){if(!t||"string"!=typeof t)return e;if(null==e)return e;const r=JSON.parse(JSON.stringify(e)),i=t.split(".");let n=r;for(let e=0;e<i.length-1;e++){const t=i[e];if(void 0===n[t])return r;n=n[t]}const s=i[i.length-1];return Array.isArray(n)?/^\d+$/.test(s)&&n.splice(parseInt(s),1):"object"==typeof n&&null!==n&&delete n[s],r}}class V{constructor(e){this.logger=e.logger,this.getSourceResolver=e.getSourceResolver}validate(e,t){return function(e,t,r){return i=this,n=void 0,o=function*(){const i=[],n=L(e,t,"",i,r);return void 0===n&&0===i.length&&void 0!==e.default?{valid:!0,value:e.default,errors:[]}:{valid:0===i.length,errors:i.length>0?i:void 0,value:n}},new((s=void 0)||(s=Promise))(function(e,t){function r(e){try{u(o.next(e))}catch(e){t(e)}}function a(e){try{u(o.throw(e))}catch(e){t(e)}}function u(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s(function(e){e(i)})).then(r,a)}u((o=o.apply(i,n||[])).next())});var i,n,s,o}(e,t,{})}}function L(e,t,r,i,n){var s,o;if(null===t){if("null"===e.type||(null===(s=e.enum)||void 0===s?void 0:s.includes(null)))return t;if(e.type&&"null"!==e.type)return void i.push({path:r,message:`Expected type ${e.type}, got null`,schema:e,value:t})}if(void 0===t)return void 0!==e.default?e.default:e.type?void i.push({path:r,message:"Required field missing",schema:e,value:t}):void 0;if(e.type&&"integer"!==e.type){const n=function(e,t){switch(e){case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"null":return null===t;case"object":return"object"==typeof t&&null!==t&&!Array.isArray(t);case"array":return Array.isArray(t);default:return!0}}(e.type,t);if(!n)return void i.push({path:r,message:`Expected type ${e.type}, got ${typeof t}`,schema:e,value:t})}if(void 0!==e.const&&t!==e.const)return void i.push({path:r,message:`Value must be exactly ${JSON.stringify(e.const)}`,schema:e,value:t});if(e.enum&&!e.enum.includes(t))return void i.push({path:r,message:`Value must be one of: ${e.enum.map(e=>JSON.stringify(e)).join(", ")}`,schema:e,value:t});let a=t;if("object"==typeof t&&!Array.isArray(t)&&e.properties){let s;s=t instanceof Error?Object.assign({name:t.name,message:t.message,stack:t.stack},t):t;const u={};if(e.required)for(const t of e.required)t in s||(void 0!==(null===(o=e.properties[t])||void 0===o?void 0:o.default)?u[t]=e.properties[t].default:i.push({path:r?`${r}.${t}`:t,message:`Required property '${t}' is missing`,schema:e.properties[t],value:void 0}));for(const[t,o]of Object.entries(s))if(e.properties&&e.properties[t]){const s=L(e.properties[t],o,r?`${r}.${t}`:t,i,n);void 0!==s&&(u[t]=s)}else u[t]=o;if(e.properties)for(const[t,r]of Object.entries(e.properties))t in u||void 0===r.default||(u[t]=r.default);a=u}if(Array.isArray(t)){if(void 0!==e.minItems&&t.length<e.minItems)return void i.push({path:r,message:`Array must have at least ${e.minItems} items, got ${t.length}`,schema:e,value:t});if(void 0!==e.maxItems&&t.length>e.maxItems)return void i.push({path:r,message:`Array must have at most ${e.maxItems} items, got ${t.length}`,schema:e,value:t});if(e.items){const s=[];if(Array.isArray(e.items))for(let o=0;o<t.length;o++){const a=e.items[o];if(a){const e=`${r}[${o}]`,u=L(a,t[o],e,i,n);void 0!==u&&s.push(u)}else s.push(t[o])}else for(let o=0;o<t.length;o++){const a=`${r}[${o}]`,u=L(e.items,t[o],a,i,n);void 0!==u&&s.push(u)}a=s}else a=t}if("string"==typeof t){if(void 0!==e.minLength&&t.length<e.minLength)return void i.push({path:r,message:`String must be at least ${e.minLength} characters long`,schema:e,value:t});if(void 0!==e.maxLength&&t.length>e.maxLength)return void i.push({path:r,message:`String must be at most ${e.maxLength} characters long`,schema:e,value:t});if(e.pattern&&!new RegExp(e.pattern).test(t))return void i.push({path:r,message:`String must match pattern: ${e.pattern}`,schema:e,value:t})}if("number"==typeof t){if(void 0!==e.minimum&&t<e.minimum)return void i.push({path:r,message:`Number must be at least ${e.minimum}`,schema:e,value:t});if(void 0!==e.maximum&&t>e.maximum)return void i.push({path:r,message:`Number must be at most ${e.maximum}`,schema:e,value:t});if("integer"===e.type&&!Number.isInteger(t))return void i.push({path:r,message:"Number must be an integer",schema:e,value:t})}if("integer"!==e.type||"number"==typeof t)return a;i.push({path:r,message:"Expected type integer, got "+typeof t,schema:e,value:t})}var _=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class B{constructor(e){this.statesByEffect={},this.logger=e.logger,this.getDatafileReader=e.getDatafileReader,this.getTransformer=e.getTransformer,this.getConditionsChecker=e.getConditionsChecker,this.modulesManager=e.modulesManager}initialize(){return _(this,void 0,void 0,function*(){const e=this.getDatafileReader(),t=e.getEffectNames(),r=yield c({datafileReader:e,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"effects_",getEntityNames:()=>e.getEffectNames(),getEntity:t=>e.getEffect(t)});for(const i of t){const t=e.getEffect(i);t&&void 0===this.statesByEffect[i]&&(void 0!==r[i]?this.statesByEffect[i]=r[i]:void 0!==t.state&&void 0===this.statesByEffect[i]&&(this.statesByEffect[i]=t.state))}})}dispatch(e){return _(this,void 0,void 0,function*(){var t,r;const{eventType:i,name:n,value:s}=e,o=this.getDatafileReader(),a=this.getConditionsChecker(),u=this.getTransformer(),l=o.getEffectNames();for(const e of l){const l=o.getEffect(e);if(l){if("event_tracked"===i){if(Array.isArray(l.on)&&!l.on.includes("event_tracked"))continue;if("object"==typeof l.on&&!(null===(t=l.on.event_tracked)||void 0===t?void 0:t.includes(n)))continue}if("attribute_set"===i){if(Array.isArray(l.on)&&!l.on.includes("attribute_set"))continue;if("object"==typeof l.on&&!(null===(r=l.on.attribute_set)||void 0===r?void 0:r.includes(n)))continue}if(l.conditions&&!(yield a.allAreMatched(l.conditions,{payload:s,eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]})))continue;if(l.steps)for(const t of l.steps){let r=!0;if(t.conditions){const r=this.getConditionsChecker();if(!(yield r.allAreMatched(t.conditions,{payload:s,eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]})))continue}if(t.handler)try{yield this.modulesManager.handle(t.handler,e,l,t,s)}catch(i){this.logger.error("Effect handler error",{effectName:e,step:t,error:i}),r=!1}if(!r&&"boolean"==typeof t.continueOnError&&!t.continueOnError)break;t.transforms&&(this.statesByEffect[e]=yield u.applyAll(this.statesByEffect[e],t.transforms,{eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]}))}yield d({datafileReader:o,conditionsChecker:a,modulesManager:this.modulesManager,storageKeyPrefix:"effects_",entityName:e,entity:l,value:this.statesByEffect[e]})}}})}refresh(){this.initialize()}getAllStates(){return this.statesByEffect}getStateValue(e){return this.statesByEffect[e]}}var q=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class K{constructor(t={}){if(this.ready=!1,this.queue=[],this.queueProcessing=!1,this.logger=t.logger||o({level:t.logLevel||s.defaultLevel}),this.datafileReader=new r({datafile:t.datafile||e,logger:this.logger}),this.emitter=new a,this.modulesManager=new m({logger:this.logger,getDatafileReader:()=>this.datafileReader,getSourceResolver:()=>this.sourceResolver}),this.validator=new V({logger:this.logger,getSourceResolver:()=>this.sourceResolver}),this.attributesManager=new f({logger:this.logger,emitter:this.emitter,validator:this.validator,getDatafileReader:()=>this.datafileReader,getTransformer:()=>this.transformer,getConditionsChecker:()=>this.conditionsChecker,modulesManager:this.modulesManager}),this.effectsManager=new B({logger:this.logger,getDatafileReader:()=>this.datafileReader,getTransformer:()=>this.transformer,getConditionsChecker:()=>this.conditionsChecker,modulesManager:this.modulesManager}),this.sourceResolver=new y({logger:this.logger,modulesManager:this.modulesManager,attributesManager:this.attributesManager,effectsManager:this.effectsManager}),this.conditionsChecker=new R({logger:this.logger,getRegex:(e,t)=>this.datafileReader.getRegex(e,t),sourceResolver:this.sourceResolver}),this.transformer=new j({logger:this.logger,conditionsChecker:this.conditionsChecker,sourceResolver:this.sourceResolver}),this.bucketer=new D({logger:this.logger,sourceResolver:this.sourceResolver,conditionsChecker:this.conditionsChecker,transformer:this.transformer}),t.modules)for(const e of t.modules)this.modulesManager.registerModule(e);Promise.all([this.effectsManager.initialize(),this.attributesManager.initialize()]).then(()=>{this.ready=!0,this.emitter.trigger("ready"),this.logger.debug("Eventvisor SDK is ready")}).catch(e=>{this.logger.error("initialization failed",e)}),this.logger.info("Eventvisor SDK initialized")}isReady(){return this.ready}onReady(){return q(this,void 0,void 0,function*(){if(!this.ready)return new Promise(e=>{const t=this.emitter.on("ready",()=>{t(),e()})})})}getRevision(){return this.datafileReader.getRevision()}setLogLevel(e){return this.logger.setLevel(e)}setDatafile(e){try{const t=new r({datafile:e,logger:this.logger});this.datafileReader=t,this.effectsManager.refresh(),this.emitter.trigger("datafile_set")}catch(e){this.logger.error("Error setting datafile",{error:e})}}on(e,t){return this.emitter.on(e,t)}addToQueue(e){this.queue.push(e)}processQueue(){return q(this,void 0,void 0,function*(){if(0===this.queue.length)return;if(this.queueProcessing)return;this.queueProcessing=!0;const e=this.queue.shift();if(e){try{"track"===e.type?yield this.trackAsync(e.name,e.value):"setAttribute"===e.type?yield this.setAttributeAsync(e.name,e.value):("removeAttribute"===e.type||"removeAttribute"===e.type)&&(yield this.removeAttributeAsync(e.name))}catch(t){this.logger.error("Error processing queue",{error:t,action:e})}this.queueProcessing=!1,yield this.processQueue()}else this.queueProcessing=!1})}setAttributeAsync(e,t){return q(this,void 0,void 0,function*(){const r=yield this.attributesManager.setAttribute(e,t);return yield this.effectsManager.dispatch({eventType:"attribute_set",name:e,value:r}),r})}setAttribute(e,t){this.addToQueue({type:"setAttribute",name:e,value:t}),this.processQueue()}getAttributeValue(e){return this.attributesManager.getAttributeValue(e)}getAttributes(){return this.attributesManager.getAttributesMap()}isAttributeSet(e){return this.attributesManager.isAttributeSet(e)}removeAttributeAsync(e){return this.attributesManager.removeAttribute(e)}removeAttribute(e){this.addToQueue({type:"removeAttribute",name:e}),this.processQueue()}registerModule(e){return this.modulesManager.registerModule(e)}removeModule(e){return this.modulesManager.removeModule(e)}trackAsync(e,t){return q(this,void 0,void 0,function*(){const r=this.datafileReader.getEvent(e);if(!r)return this.logger.error("Event schema not found in datafile",{eventName:e}),null;const i=r.level||"info";r.deprecated&&this.logger.warn("Event is deprecated",{eventName:e});const n=yield this.validator.validate(r,t);if(!n.valid)return this.logger.warn("Event validation failed",{eventName:e,errors:n.errors}),null;const s=n.value;if(r.conditions&&!(yield this.conditionsChecker.allAreMatched(r.conditions,{eventName:e,eventLevel:i,payload:s})))return this.logger.debug("Event conditions not matched",{eventName:e,conditions:r.conditions}),null;if(r.sample){const t=yield this.bucketer.isSampled(r.sample,{eventName:e,eventLevel:i,payload:s});if(!t.isSampled)return this.logger.debug("Event sample not matched",{eventName:e,matchedSample:t.matchedSample,bucketedNumber:t.bucketedNumber,bucketKey:t.bucketKey}),null}let o=s;r.transforms&&(o=yield this.transformer.applyAll(s,r.transforms,{eventName:e,eventLevel:i,payload:s})),yield this.effectsManager.dispatch({eventType:"event_tracked",name:e,value:o});const a=this.datafileReader.getDestinationNames();for(const t of a){const n=this.datafileReader.getDestination(t);if(!n)continue;if(!this.modulesManager.transportExists(n.transport)){this.logger.error("Destination has no transport",{eventName:e,destinationName:t});continue}let s=o;if(r.destinations&&void 0!==r.destinations[t]){const n=r.destinations[t];if(!1===n){this.logger.debug("Event has destination disabled",{eventName:e,destinationName:t});continue}if("object"==typeof n&&n.conditions){if(!(yield this.conditionsChecker.allAreMatched(n.conditions,{eventName:e,eventLevel:i,payload:s}))){this.logger.debug("Destination conditions not matched for event",{eventName:e,destinationName:t});continue}if(n.sample){const r=yield this.bucketer.isSampled(n.sample,{eventName:e,eventLevel:i,payload:s});if(!r.isSampled){this.logger.debug("Destination sample not matched for event",{eventName:e,destinationName:t,matchedSample:r.matchedSample,bucketedNumber:r.bucketedNumber,bucketKey:r.bucketKey});continue}}n.transforms&&(s=yield this.transformer.applyAll(o,n.transforms,{eventName:e,eventLevel:i,payload:s}))}}!n.conditions||(yield this.conditionsChecker.allAreMatched(n.conditions,{eventName:e,eventLevel:i,payload:o}))?!n.sample||(yield this.bucketer.isSampled(n.sample,{eventName:e,eventLevel:i,payload:s})).isSampled?(n.transforms&&(s=yield this.transformer.applyAll(s,n.transforms,{eventName:e,eventLevel:i,payload:s,destinationName:t,attributes:this.attributesManager.getAttributesMap()})),yield this.modulesManager.transport(n.transport,t,e,s,i)):this.logger.debug("Destination sample not matched",{eventName:e,destinationName:t}):this.logger.debug("Destination conditions not matched",{eventName:e,destinationName:t})}return o})}track(e,t){this.addToQueue({type:"track",name:e,value:t}),this.processQueue()}getStateValue(e){return this.effectsManager.getStateValue(e)}spawn(){}}function I(e={}){return new K(e)}export{f as AttributesManager,D as Bucketer,$ as BucketerOptions,r as DatafileReader,B as EffectsManager,a as Emitter,K as Eventvisor,s as Logger,P as MAX_BUCKETED_NUMBER,m as ModulesManager,E as MurmurHashV3,y as SourceResolver,j as Transformer,w as compareSegments,x as compareVersions,I as createInstance,o as createLogger,n as defaultLogHandler,e as emptyDatafile,T as getBucketedNumber,t as getComplexPersists,i as loggerPrefix,b as semver,A as validateAndParse};
1
+ const e={schemaVersion:"1",revision:"0",attributes:{},events:{},destinations:{},effects:{}};function t(e){let r=[];if("string"==typeof e)r.push({storage:e});else if(Array.isArray(e))for(const i of e){const e=t(i);e&&(r=r.concat(e))}else"object"==typeof e&&r.push(e);return r}class r{constructor(e){const{datafile:t,logger:r}=e;this.datafile=t,this.schemaVersion=t.schemaVersion,this.revision=t.revision,this.regexCache={},this.logger=r}getSchemaVersion(){return this.schemaVersion}getRevision(){return this.revision}getAttribute(e){return this.datafile.attributes[e]}getAttributeNames(){return Object.keys(this.datafile.attributes)}getEvent(e){return this.datafile.events[e]}getDestination(e){return this.datafile.destinations[e]}getDestinationNames(){return Object.keys(this.datafile.destinations)}getEffect(e){return this.datafile.effects[e]}getEffectNames(){return Object.keys(this.datafile.effects)}getRegex(e,t){const r=t||"",i=`${e}-${r}`;if(this.regexCache[i])return this.regexCache[i];const n=new RegExp(e,r);return this.regexCache[i]=n,n}getPersists(e){return e&&e.persist?t(e.persist):null}}const i="[Eventvisor]",n=function(e,t,r={}){let n="log";"info"===e?n="info":"warn"===e?n="warn":"error"===e&&(n="error"),console[n](i,t,r)};class s{constructor(e){this.level=e.level||s.defaultLevel,this.handle=e.handler||n}setLevel(e){this.level=e}log(e,t,r){s.allLevels.indexOf(this.level)>=s.allLevels.indexOf(e)&&this.handle(e,t,r)}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}}function o(e={}){return new s(e)}s.allLevels=["fatal","error","warn","info","debug"],s.defaultLevel="info";class a{constructor(){this.listeners={}}on(e,t){this.listeners[e]||(this.listeners[e]=[]);const r=this.listeners[e];r.push(t);let i=!0;return function(){if(!i)return;i=!1;const e=r.indexOf(t);-1!==e&&r.splice(e,1)}}trigger(e,t={}){const r=this.listeners[e];r&&r.forEach(function(e){try{e(t)}catch(e){console.error(e)}})}clearAll(){this.listeners={}}}var u=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};function l(e){return u(this,void 0,void 0,function*(){const{persists:t,entityName:r,conditionsChecker:i,payload:n}=e;for(const e of t){if(!e.conditions)return e;if(yield i.allAreMatched(e.conditions,{attributeName:r,effectName:r,payload:n}))return e}})}function c(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,getEntityNames:n,getEntity:s}){const o=n(),a={};for(const n of o){const o=s(n);if(!o)continue;const u=e.getPersists(o);if(!u)continue;const c=yield l({persists:u,entityName:n,conditionsChecker:t,payload:{}});if(!c)continue;const d=yield r.readFromStorage(c.storage,`${i}${n}`);null!=d&&(a[n]=d)}return a})}function d(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,entityName:n,entity:s,value:o}){if(!s)return;const a=e.getPersists(s);if(!a)return;const u=yield l({persists:a,entityName:n,conditionsChecker:t,payload:o});u&&(yield r.writeToStorage(u.storage,`${i}${n}`,o))})}var h=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class f{constructor(e){const{logger:t,getDatafileReader:r,emitter:i,getTransformer:n,getConditionsChecker:s,validator:o,modulesManager:a}=e;this.logger=t,this.getDatafileReader=r,this.emitter=i,this.getTransformer=n,this.getConditionsChecker=s,this.validator=o,this.modulesManager=a,this.attributesMap={}}initialize(){return h(this,void 0,void 0,function*(){yield this.initializeFromStorage()})}initializeFromStorage(){return h(this,void 0,void 0,function*(){const e=this.getDatafileReader(),t=yield c({datafileReader:e,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",getEntityNames:()=>e.getAttributeNames(),getEntity:t=>e.getAttribute(t)});this.attributesMap=t})}setAttribute(e,t){return h(this,void 0,void 0,function*(){const r=this.getDatafileReader(),i=r.getAttribute(e);if(!i)return this.logger.error("Attribute schema not found",{attributeName:e}),null;i.deprecated&&this.logger.warn("Attribute is deprecated",{attributeName:e});const n=yield this.validator.validate(i,t);if(!n.valid)return this.logger.warn("Attribute validation failed",{attributeName:e,errors:n.errors}),null;const s=n.value,o=i.transforms?yield this.getTransformer().applyAll(s,i.transforms,{payload:s,attributeName:e}):s;return this.attributesMap[e]=o,this.emitter.trigger("attribute_set",{attributeName:e}),this.logger.debug("Attribute set",{attributeName:e}),yield d({datafileReader:r,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",entityName:e,entity:i,value:t}),o})}isAttributeSet(e){return void 0!==this.attributesMap[e]}getAttributesMap(){return this.attributesMap}getAttributeValue(e){return this.attributesMap[e]||null}removeAttribute(e){return h(this,void 0,void 0,function*(){const t=this.getDatafileReader();yield function(e){return u(this,arguments,void 0,function*({datafileReader:e,conditionsChecker:t,modulesManager:r,storageKeyPrefix:i,entityName:n,entity:s}){if(!s)return;const o=e.getPersists(s);if(!o)return;const a=yield l({persists:o,entityName:n,conditionsChecker:t,payload:{}});a&&(yield r.removeFromStorage(a.storage,`${i}${n}`))})}({datafileReader:t,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"attributes_",entityName:e,entity:t.getAttribute(e)}),delete this.attributesMap[e],this.emitter.trigger("attribute_removed",{attributeName:e})})}}var g=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class m{constructor(e){const{logger:t,getDatafileReader:r,getSourceResolver:i}=e;this.logger=t,this.getDatafileReader=r,this.getSourceResolver=i,this.modules=[]}registerModule(e){this.modules.find(t=>t.name===e.name)?this.logger.error(`Module ${e.name} already registered`):this.modules.push(e)}getModule(e){return this.modules.find(t=>t.name===e)}removeModule(e){this.getModule(e)?this.modules=this.modules.filter(t=>t.name!==e):this.logger.error(`Module ${e} not found`)}getModuleDependencies(){return{datafileReader:this.getDatafileReader(),logger:this.logger,sourceResolver:this.getSourceResolver()}}lookup(e){return g(this,void 0,void 0,function*(){const[t,...r]=e.split("."),i=r.join("."),n=this.getModule(t);if(n&&n.lookup)try{return yield n.lookup({key:i},this.getModuleDependencies())}catch(e){return this.logger.error("Error in lookup",{moduleName:t,key:i,error:e}),null}return this.logger.error(`Module "${t}" not found with "lookup" function`),null})}handle(e,t,r,i,n){return g(this,void 0,void 0,function*(){const[s,o]=e.split("."),a=this.getModule(s);if(a&&a.handle)try{return yield a.handle({effectName:t,effect:r,step:i,payload:n},this.getModuleDependencies())}catch(e){return void this.logger.error("Error in handle",{moduleName:s,effectName:t,error:e})}this.logger.error(`Module "${s}" not found with "handle" function`)})}transportExists(e){const[t,r]=e.split("."),i=this.getModule(t);return!(!i||!i.transport)}transport(e,t,r,i,n,s){return g(this,void 0,void 0,function*(){const[o,a]=e.split("."),u=this.getModule(o);if(u&&u.transport)try{return yield u.transport({destinationName:t,eventName:r,eventLevel:n,payload:i,error:s},this.getModuleDependencies())}catch(e){return void this.logger.error("Error in transport",{moduleName:o,destinationName:t,eventName:r,error:e})}this.logger.error(`Module "${o}" not found with "transport" function`)})}readFromStorage(e,t){return g(this,void 0,void 0,function*(){const r=this.getModule(e);if(r&&r.readFromStorage)try{return yield r.readFromStorage({key:t},this.getModuleDependencies())}catch(r){return this.logger.error("Error in readFromStorage",{moduleName:e,key:t,error:r}),null}return this.logger.error(`Module "${e}" not found with "readFromStorage" function`),null})}writeToStorage(e,t,r){return g(this,void 0,void 0,function*(){const i=this.getModule(e);if(i&&i.writeToStorage)try{return yield i.writeToStorage({key:t,value:r},this.getModuleDependencies())}catch(i){return void this.logger.error("Error in writeToStorage",{moduleName:e,key:t,value:r,error:i})}this.logger.error(`Module "${e}" not found with "writeToStorage" function`)})}removeFromStorage(e,t){return g(this,void 0,void 0,function*(){const r=this.getModule(e);if(r&&r.removeFromStorage)try{return yield r.removeFromStorage({key:t},this.getModuleDependencies())}catch(r){return void this.logger.error("Error in removeFromStorage",{moduleName:e,key:t,error:r})}this.logger.error(`Module "${e}" not found with "removeFromStorage" function`)})}}var v=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};function p(e,t){return t.reduce((e,t)=>e[t],e)}class y{constructor(e){const{logger:t,modulesManager:r,attributesManager:i,effectsManager:n}=e;this.logger=t,this.modulesManager=r,this.attributesManager=i,this.effectsManager=n}getPath(e){const t=e.split(".");return{name:t[0],path:t.slice(1),fullKey:e}}getOrigin(e){if("string"==typeof e){const t=e.split(".");return{originType:t[0],name:t[1],path:t.slice(2),fullKey:e}}return"source"in e||"source"in e?this.getOrigin(e.source):"attribute"in e?Object.assign({originType:"attribute"},this.getPath(e.attribute)):"effect"in e?Object.assign({originType:"effect"},this.getPath(e.effect)):"payload"in e?Array.isArray(e.payload)?e.payload.map(e=>Object.assign({originType:"payload"},this.getPath(e))):Object.assign({originType:"payload"},this.getPath(e.payload)):"lookup"in e?Object.assign({originType:"lookup"},this.getPath(e.lookup)):"state"in e?Object.assign({originType:"state"},this.getPath(e.state)):null}resolveByOrigin(e){return v(this,arguments,void 0,function*(e,t={}){if(null===e)return null;if("attributes"===e.originType){const t=e.name?this.attributesManager.getAttributeValue(e.name):this.attributesManager.getAttributesMap();return e.path.length>0?p(t,e.path):t}if("attribute"===e.originType){const t=this.attributesManager.getAttributeValue(e.name);return e.path.length>0?p(t,e.path):t}if("effects"===e.originType){const t=e.name?this.effectsManager.getStateValue(e.name):this.effectsManager.getAllStates();return e.path.length>0?p(t,e.path):t}if("effect"===e.originType){const t=this.effectsManager.getStateValue(e.name);return e.path.length>0?p(t,e.path):t}return"lookup"===e.originType?this.modulesManager.lookup(e.fullKey):void 0!==t[e.originType]?p(t[e.originType],[e.name,...e.path].filter(Boolean)):null})}resolve(e){return v(this,arguments,void 0,function*(e,t={}){const r=this.getOrigin(e);return Array.isArray(r)?Promise.all(r.map(e=>this.resolveByOrigin(e,t))):yield this.resolveByOrigin(r,t)})}}const b=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,A=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(b);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},M=e=>"*"===e||"x"===e||"X"===e,N=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},k=(e,t)=>{if(M(e)||M(t))return 0;const[r,i]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(N(e),N(t));return r>i?1:r<i?-1:0},w=(e,t)=>{for(let r=0;r<Math.max(e.length,t.length);r++){const i=k(e[r]||"0",t[r]||"0");if(0!==i)return i}return 0},x=(e,t)=>{const r=A(e),i=A(t),n=r.pop(),s=i.pop(),o=w(r,i);return 0!==o?o:n&&s?w(n.split("."),s.split(".")):n||s?n?-1:1:0};var S=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class R{constructor(e){this.getRegex=e.getRegex,this.sourceResolver=e.sourceResolver,this.logger=e.logger}isMatched(e,t){return S(this,void 0,void 0,function*(){const{operator:r,value:i,regexFlags:n}=e,s=yield this.sourceResolver.resolve(e,t);if("equals"===r)return s===i;if("notEquals"===r)return s!==i;if("before"===r||"after"===r){const e=s instanceof Date?s:new Date(s),t=i instanceof Date?i:new Date(i);return"before"===r?e<t:e>t}if(!Array.isArray(i)||-1===["string","number"].indexOf(typeof s)&&null!==s)if("string"==typeof s&&"string"==typeof i){const e=s;if("contains"===r)return-1!==e.indexOf(i);if("notContains"===r)return-1===e.indexOf(i);if("startsWith"===r)return e.startsWith(i);if("endsWith"===r)return e.endsWith(i);if("semverEquals"===r)return 0===x(e,i);if("semverNotEquals"===r)return 0!==x(e,i);if("semverGreaterThan"===r)return 1===x(e,i);if("semverGreaterThanOrEquals"===r)return x(e,i)>=0;if("semverLessThan"===r)return-1===x(e,i);if("semverLessThanOrEquals"===r)return x(e,i)<=0;if("matches"===r)return this.getRegex(i,n||"").test(e);if("notMatches"===r)return!this.getRegex(i,n||"").test(e)}else if("number"==typeof s&&"number"==typeof i){if("greaterThan"===r)return s>i;if("greaterThanOrEquals"===r)return s>=i;if("lessThan"===r)return s<i;if("lessThanOrEquals"===r)return s<=i}else{if("exists"===r)return void 0!==s;if("notExists"===r)return void 0===s;if(Array.isArray(s)&&"string"==typeof i){const e=s;if("includes"===r)return e.indexOf(i)>-1;if("notIncludes"===r)return-1===e.indexOf(i)}}else{const e=s;if("in"===r)return-1!==i.indexOf(e);if("notIn"===r)return-1===i.indexOf(e)}return!1})}_allAreMatched(e,t){return S(this,void 0,void 0,function*(){if("string"==typeof e)return"*"===e;if("operator"in e)try{return this.isMatched(e,t)}catch(t){return this.logger.warn(t.message,{error:t,details:{condition:e}}),!1}if("and"in e&&Array.isArray(e.and)){for(const r of e.and)if(!(yield this._allAreMatched(r,t)))return!1;return!0}if("or"in e&&Array.isArray(e.or)){for(const r of e.or)if(yield this._allAreMatched(r,t))return!0;return!1}if("not"in e&&Array.isArray(e.not)){for(const r of e.not)if(yield this._allAreMatched(r,t))return!1;return!0}if(Array.isArray(e)){let r=!0;for(const i of e)if(!(yield this._allAreMatched(i,t))){r=!1;break}return r}return!1})}allAreMatched(e,t){return S(this,void 0,void 0,function*(){const r=this.parseIfStringified(e);return this._allAreMatched(r,t)})}parseIfStringified(e){if("string"!=typeof e)return e;if("*"===e)return e;try{return JSON.parse(e)}catch(t){return this.logger.error("Error parsing conditions",{error:t,details:{conditions:e}}),e}}}function E(e,t){var r;let i,n,s,o,a,u,l,c;for("string"==typeof e&&(r=e,e=(new TextEncoder).encode(r)),i=3&e.length,n=e.length-i,s=t,a=3432918353,u=461845907,c=0;c<n;)l=255&e[c]|(255&e[++c])<<8|(255&e[++c])<<16|(255&e[++c])<<24,++c,l=(65535&l)*a+(((l>>>16)*a&65535)<<16)&4294967295,l=l<<15|l>>>17,l=(65535&l)*u+(((l>>>16)*u&65535)<<16)&4294967295,s^=l,s=s<<13|s>>>19,o=5*(65535&s)+((5*(s>>>16)&65535)<<16)&4294967295,s=27492+(65535&o)+(((o>>>16)+58964&65535)<<16);switch(l=0,i){case 3:l^=(255&e[c+2])<<16;case 2:l^=(255&e[c+1])<<8;case 1:l^=255&e[c],l=(65535&l)*a+(((l>>>16)*a&65535)<<16)&4294967295,l=l<<15|l>>>17,l=(65535&l)*u+(((l>>>16)*u&65535)<<16)&4294967295,s^=l}return s^=e.length,s^=s>>>16,s=2246822507*(65535&s)+((2246822507*(s>>>16)&65535)<<16)&4294967295,s^=s>>>13,s=3266489909*(65535&s)+((3266489909*(s>>>16)&65535)<<16)&4294967295,s^=s>>>16,s>>>0}var C=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};const O=Math.pow(2,32),P=1e5;function T(e){const t=E(e,1)/O;return Math.floor(t*P)}class ${}class D{constructor(e){this.logger=e.logger,this.sourceResolver=e.sourceResolver,this.conditionsChecker=e.conditionsChecker,this.transformer=e.transformer}getBucketKey(e,t){return C(this,void 0,void 0,function*(){let r,i;if("string"==typeof e)r="plain",i=[e];else if(Array.isArray(e))r="and",i=e;else if("object"==typeof e&&"or"in e&&Array.isArray(e.or))r="or",i=e.or;else{if("object"!=typeof e)throw this.logger.error("invalid sampleBy",{sampleBy:e}),new Error("invalid sampleBy");r="and",i=[e]}const n=[];for(const e of i){const i=yield this.sourceResolver.resolve(e,t);void 0!==i&&("plain"===r||"and"===r||0===n.length)&&n.push(String(i))}return n.join(".")})}isSampled(e,t){return C(this,void 0,void 0,function*(){const r=(Array.isArray(e)?e:[e]).find(e=>C(this,void 0,void 0,function*(){return!e.conditions||(yield this.conditionsChecker.allAreMatched(e.conditions,t))}));if(r){const e=yield this.getBucketKey(r.by,t),i=T(e);if(r.percentage&&r.percentage>0&&i<r.percentage)return{isSampled:!1,matchedSample:r,bucketedNumber:i,bucketKey:e};if(r.range&&i<r.range[0]&&i>r.range[1])return{isSampled:!1,matchedSample:r,bucketedNumber:i,bucketKey:e}}return{isSampled:!0}})}}class j{constructor(e){this.logger=e.logger,this.conditionsChecker=e.conditionsChecker,this.sourceResolver=e.sourceResolver}applyAll(e,t){return r=this,i=arguments,s=function*(e,t,r={}){let i=e;for(const n of t){if(n.conditions&&!(yield this.conditionsChecker.allAreMatched(n.conditions,r)))continue;let t=yield this.sourceResolver.resolve(n,r);if(null==t&&n.target&&(t=yield this.sourceResolver.resolve({payload:n.target},void 0===r.payload?Object.assign(Object.assign({},r),{payload:e}):r)),n.target){const e=Array.isArray(n.target)?n.target:[n.target];for(const r of e){if("string"==typeof t&&"trim"===n.type&&(i=j.setValueAtPath(i,r,t.trim())),Array.isArray(t)&&"concat"===n.type){const e=n.separator||" ";i=j.setValueAtPath(i,r,t.join(e))}if("set"===n.type&&(i="value"in n?j.setValueAtPath(i,r,n.value):j.setValueAtPath(i,r,t)),"remove"===n.type&&(i=j.removeValueAt(i,r)),"toInteger"===n.type)i=j.setValueAtPath(i,r,parseInt(String(t)));else if("toDouble"===n.type)i=j.setValueAtPath(i,r,parseFloat(String(t)));else if("toString"===n.type)i=j.setValueAtPath(i,r,String(t)||"");else if("toBoolean"===n.type){const e=String(t).toLowerCase();i=j.setValueAtPath(i,r,-1!==["true","1","checked","yes","on","y"].indexOf(e)||!0===t)}}}else"set"===n.type&&"value"in n&&(i=n.value);if("spread"===n.type)if(n.target){const e=j.getValueAtPath(i,n.target);i=j.setValueAtPath(i,n.target,Object.assign(Object.assign({},e||{}),t||{}))}else i=Object.assign(Object.assign({},i||{}),t||{});if("increment"===n.type){const e="number"==typeof n.value?n.value:1;n.target?i=j.setValueAtPath(i,n.target,Number(t)+e):i+=e}else if("decrement"===n.type){const e="number"==typeof n.value?n.value:1;n.target?i=j.setValueAtPath(i,n.target,Number(t)-e):i-=e}if(n.targetMap){const e=[];if(Array.isArray(n.targetMap))for(const t of n.targetMap)Object.entries(t).forEach(([t,r])=>{e.push({[t]:r})});else Object.entries(n.targetMap).forEach(([t,r])=>{e.push({[t]:r})});for(const t of e)"rename"===n.type&&(i=j.renameValueAt(i,t))}}return i},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{u(s.next(e))}catch(e){t(e)}}function a(e){try{u(s.throw(e))}catch(e){t(e)}}function u(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}u((s=s.apply(r,i||[])).next())});var r,i,n,s}static renameValueAt(e,t){if(!e||"object"!=typeof e)return e;if(!t||"object"!=typeof t)return e;const r=Object.entries(t);if(0===r.length)return e;const[i,n]=r[0];if(!i||!n)return e;const s=j.getValueAtPath(e,i);if(void 0===s)return e;const o=JSON.parse(JSON.stringify(e)),a=i.split(".");let u=o;for(let e=0;e<a.length-1;e++){const t=a[e];if(void 0===u[t])return o;u=u[t]}return delete u[a[a.length-1]],j.setValueAtPath(o,n,s)}static getValueAtPath(e,t){if(!t||"string"!=typeof t)return;const r=t.split(".");let i=e;for(const e of r){if(null==i)return;if("object"!=typeof i||Array.isArray(i)){if(!Array.isArray(i)||!/^\d+$/.test(e))return;i=i[parseInt(e)]}else i=i[e]}return i}static setValueAtPath(e,t,r){if(!t||"string"!=typeof t)return e;if(null==e)return e;const i=JSON.parse(JSON.stringify(e)),n=t.split(".");let s=i;for(let e=0;e<n.length-1;e++){const t=n[e];void 0===s[t]&&(/^\d+$/.test(n[e+1])?s[t]=[]:s[t]={}),s=s[t]}return s[n[n.length-1]]=r,i}static removeValueAt(e,t){if(!t||"string"!=typeof t)return e;if(null==e)return e;const r=JSON.parse(JSON.stringify(e)),i=t.split(".");let n=r;for(let e=0;e<i.length-1;e++){const t=i[e];if(void 0===n[t])return r;n=n[t]}const s=i[i.length-1];return Array.isArray(n)?/^\d+$/.test(s)&&n.splice(parseInt(s),1):"object"==typeof n&&null!==n&&delete n[s],r}}class V{constructor(e){this.logger=e.logger,this.getSourceResolver=e.getSourceResolver}validate(e,t){return function(e,t,r){return i=this,n=void 0,o=function*(){const i=[],n=L(e,t,"",i,r);return void 0===n&&0===i.length&&void 0!==e.default?{valid:!0,value:e.default,errors:[]}:{valid:0===i.length,errors:i.length>0?i:void 0,value:n}},new((s=void 0)||(s=Promise))(function(e,t){function r(e){try{u(o.next(e))}catch(e){t(e)}}function a(e){try{u(o.throw(e))}catch(e){t(e)}}function u(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s(function(e){e(i)})).then(r,a)}u((o=o.apply(i,n||[])).next())});var i,n,s,o}(e,t,{})}}function L(e,t,r,i,n){var s,o;if(null===t){if("null"===e.type||(null===(s=e.enum)||void 0===s?void 0:s.includes(null)))return t;if(e.type&&"null"!==e.type)return void i.push({path:r,message:`Expected type ${e.type}, got null`,schema:e,value:t})}if(void 0===t)return void 0!==e.default?e.default:e.type?void i.push({path:r,message:"Required field missing",schema:e,value:t}):void 0;if(e.type&&"integer"!==e.type){const n=function(e,t){switch(e){case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"null":return null===t;case"object":return"object"==typeof t&&null!==t&&!Array.isArray(t);case"array":return Array.isArray(t);default:return!0}}(e.type,t);if(!n)return void i.push({path:r,message:`Expected type ${e.type}, got ${typeof t}`,schema:e,value:t})}if(void 0!==e.const&&t!==e.const)return void i.push({path:r,message:`Value must be exactly ${JSON.stringify(e.const)}`,schema:e,value:t});if(e.enum&&!e.enum.includes(t))return void i.push({path:r,message:`Value must be one of: ${e.enum.map(e=>JSON.stringify(e)).join(", ")}`,schema:e,value:t});let a=t;if("object"==typeof t&&!Array.isArray(t)&&e.properties){let s;s=t instanceof Error?Object.assign({name:t.name,message:t.message,stack:t.stack},t):t;const u={};if(e.required)for(const t of e.required)t in s||(void 0!==(null===(o=e.properties[t])||void 0===o?void 0:o.default)?u[t]=e.properties[t].default:i.push({path:r?`${r}.${t}`:t,message:`Required property '${t}' is missing`,schema:e.properties[t],value:void 0}));for(const[t,o]of Object.entries(s))if(e.properties&&e.properties[t]){const s=L(e.properties[t],o,r?`${r}.${t}`:t,i,n);void 0!==s&&(u[t]=s)}else u[t]=o;if(e.properties)for(const[t,r]of Object.entries(e.properties))t in u||void 0===r.default||(u[t]=r.default);a=u}if(Array.isArray(t)){if(void 0!==e.minItems&&t.length<e.minItems)return void i.push({path:r,message:`Array must have at least ${e.minItems} items, got ${t.length}`,schema:e,value:t});if(void 0!==e.maxItems&&t.length>e.maxItems)return void i.push({path:r,message:`Array must have at most ${e.maxItems} items, got ${t.length}`,schema:e,value:t});if(e.items){const s=[];if(Array.isArray(e.items))for(let o=0;o<t.length;o++){const a=e.items[o];if(a){const e=`${r}[${o}]`,u=L(a,t[o],e,i,n);void 0!==u&&s.push(u)}else s.push(t[o])}else for(let o=0;o<t.length;o++){const a=`${r}[${o}]`,u=L(e.items,t[o],a,i,n);void 0!==u&&s.push(u)}a=s}else a=t}if("string"==typeof t){if(void 0!==e.minLength&&t.length<e.minLength)return void i.push({path:r,message:`String must be at least ${e.minLength} characters long`,schema:e,value:t});if(void 0!==e.maxLength&&t.length>e.maxLength)return void i.push({path:r,message:`String must be at most ${e.maxLength} characters long`,schema:e,value:t});if(e.pattern&&!new RegExp(e.pattern).test(t))return void i.push({path:r,message:`String must match pattern: ${e.pattern}`,schema:e,value:t})}if("number"==typeof t){if(void 0!==e.minimum&&t<e.minimum)return void i.push({path:r,message:`Number must be at least ${e.minimum}`,schema:e,value:t});if(void 0!==e.maximum&&t>e.maximum)return void i.push({path:r,message:`Number must be at most ${e.maximum}`,schema:e,value:t});if("integer"===e.type&&!Number.isInteger(t))return void i.push({path:r,message:"Number must be an integer",schema:e,value:t})}if("integer"!==e.type||"number"==typeof t)return a;i.push({path:r,message:"Expected type integer, got "+typeof t,schema:e,value:t})}var _=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class B{constructor(e){this.statesByEffect={},this.logger=e.logger,this.getDatafileReader=e.getDatafileReader,this.getTransformer=e.getTransformer,this.getConditionsChecker=e.getConditionsChecker,this.modulesManager=e.modulesManager}initialize(){return _(this,void 0,void 0,function*(){const e=this.getDatafileReader(),t=e.getEffectNames(),r=yield c({datafileReader:e,conditionsChecker:this.getConditionsChecker(),modulesManager:this.modulesManager,storageKeyPrefix:"effects_",getEntityNames:()=>e.getEffectNames(),getEntity:t=>e.getEffect(t)});for(const i of t){const t=e.getEffect(i);t&&void 0===this.statesByEffect[i]&&(void 0!==r[i]?this.statesByEffect[i]=r[i]:void 0!==t.state&&void 0===this.statesByEffect[i]&&(this.statesByEffect[i]=t.state))}})}dispatch(e){return _(this,void 0,void 0,function*(){var t,r;const{eventType:i,name:n,value:s}=e,o=this.getDatafileReader(),a=this.getConditionsChecker(),u=this.getTransformer(),l=o.getEffectNames();for(const e of l){const l=o.getEffect(e);if(l){if("event_tracked"===i){if(Array.isArray(l.on)&&!l.on.includes("event_tracked"))continue;if("object"==typeof l.on&&!(null===(t=l.on.event_tracked)||void 0===t?void 0:t.includes(n)))continue}if("attribute_set"===i){if(Array.isArray(l.on)&&!l.on.includes("attribute_set"))continue;if("object"==typeof l.on&&!(null===(r=l.on.attribute_set)||void 0===r?void 0:r.includes(n)))continue}if(l.conditions&&!(yield a.allAreMatched(l.conditions,{payload:s,eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]})))continue;if(l.steps)for(const t of l.steps){let r=!0;if(t.conditions){const r=this.getConditionsChecker();if(!(yield r.allAreMatched(t.conditions,{payload:s,eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]})))continue}if(t.handler)try{yield this.modulesManager.handle(t.handler,e,l,t,s)}catch(i){this.logger.error("Effect handler error",{effectName:e,step:t,error:i}),r=!1}if(!r&&"boolean"==typeof t.continueOnError&&!t.continueOnError)break;t.transforms&&(this.statesByEffect[e]=yield u.applyAll(this.statesByEffect[e],t.transforms,{eventName:"event_tracked"===i?n:void 0,attributeName:"attribute_set"===i?n:void 0,state:this.statesByEffect[e]}))}yield d({datafileReader:o,conditionsChecker:a,modulesManager:this.modulesManager,storageKeyPrefix:"effects_",entityName:e,entity:l,value:this.statesByEffect[e]})}}})}refresh(){this.initialize()}getAllStates(){return this.statesByEffect}getStateValue(e){return this.statesByEffect[e]}}var q=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{u(i.next(e))}catch(e){s(e)}}function a(e){try{u(i.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((i=i.apply(e,t||[])).next())})};class K{constructor(t={}){if(this.ready=!1,this.queue=[],this.queueProcessing=!1,this.logger=t.logger||o({level:t.logLevel||s.defaultLevel}),this.datafileReader=new r({datafile:t.datafile||e,logger:this.logger}),this.emitter=new a,this.modulesManager=new m({logger:this.logger,getDatafileReader:()=>this.datafileReader,getSourceResolver:()=>this.sourceResolver}),this.validator=new V({logger:this.logger,getSourceResolver:()=>this.sourceResolver}),this.attributesManager=new f({logger:this.logger,emitter:this.emitter,validator:this.validator,getDatafileReader:()=>this.datafileReader,getTransformer:()=>this.transformer,getConditionsChecker:()=>this.conditionsChecker,modulesManager:this.modulesManager}),this.effectsManager=new B({logger:this.logger,getDatafileReader:()=>this.datafileReader,getTransformer:()=>this.transformer,getConditionsChecker:()=>this.conditionsChecker,modulesManager:this.modulesManager}),this.sourceResolver=new y({logger:this.logger,modulesManager:this.modulesManager,attributesManager:this.attributesManager,effectsManager:this.effectsManager}),this.conditionsChecker=new R({logger:this.logger,getRegex:(e,t)=>this.datafileReader.getRegex(e,t),sourceResolver:this.sourceResolver}),this.transformer=new j({logger:this.logger,conditionsChecker:this.conditionsChecker,sourceResolver:this.sourceResolver}),this.bucketer=new D({logger:this.logger,sourceResolver:this.sourceResolver,conditionsChecker:this.conditionsChecker,transformer:this.transformer}),t.modules)for(const e of t.modules)this.modulesManager.registerModule(e);Promise.all([this.effectsManager.initialize(),this.attributesManager.initialize()]).then(()=>{this.ready=!0,this.emitter.trigger("ready"),this.logger.debug("Eventvisor SDK is ready")}).catch(e=>{this.logger.error("initialization failed",e)}),this.logger.info("Eventvisor SDK initialized")}isReady(){return this.ready}onReady(){return q(this,void 0,void 0,function*(){if(!this.ready)return new Promise(e=>{const t=this.emitter.on("ready",()=>{t(),e()})})})}getRevision(){return this.datafileReader.getRevision()}setLogLevel(e){return this.logger.setLevel(e)}setDatafile(e){try{const t=new r({datafile:e,logger:this.logger});this.datafileReader=t,this.effectsManager.refresh(),this.emitter.trigger("datafile_set")}catch(e){this.logger.error("Error setting datafile",{error:e})}}on(e,t){return this.emitter.on(e,t)}addToQueue(e){this.queue.push(e)}processQueue(){return q(this,void 0,void 0,function*(){if(0===this.queue.length)return;if(this.queueProcessing)return;this.queueProcessing=!0;const e=this.queue.shift();if(e){try{"track"===e.type?yield this.trackAsync(e.name,e.value):"setAttribute"===e.type?yield this.setAttributeAsync(e.name,e.value):"removeAttribute"===e.type&&(yield this.removeAttributeAsync(e.name))}catch(t){this.logger.error("Error processing queue",{error:t,action:e})}this.queueProcessing=!1,yield this.processQueue()}else this.queueProcessing=!1})}setAttributeAsync(e,t){return q(this,void 0,void 0,function*(){const r=yield this.attributesManager.setAttribute(e,t);return yield this.effectsManager.dispatch({eventType:"attribute_set",name:e,value:r}),r})}setAttribute(e,t){this.addToQueue({type:"setAttribute",name:e,value:t}),this.processQueue()}getAttributeValue(e){return this.attributesManager.getAttributeValue(e)}getAttributes(){return this.attributesManager.getAttributesMap()}isAttributeSet(e){return this.attributesManager.isAttributeSet(e)}removeAttributeAsync(e){return this.attributesManager.removeAttribute(e)}removeAttribute(e){this.addToQueue({type:"removeAttribute",name:e}),this.processQueue()}registerModule(e){return this.modulesManager.registerModule(e)}removeModule(e){return this.modulesManager.removeModule(e)}trackAsync(e,t){return q(this,void 0,void 0,function*(){const r=this.datafileReader.getEvent(e);if(!r)return this.logger.error("Event schema not found in datafile",{eventName:e}),null;const i=r.level||"info";r.deprecated&&this.logger.warn("Event is deprecated",{eventName:e});let n=t instanceof Error?t:void 0;const s=yield this.validator.validate(r,t);if(!s.valid)return this.logger.warn("Event validation failed",{eventName:e,errors:s.errors}),null;const o=s.value;if(r.conditions&&!(yield this.conditionsChecker.allAreMatched(r.conditions,{eventName:e,eventLevel:i,payload:o})))return this.logger.debug("Event conditions not matched",{eventName:e,conditions:r.conditions}),null;if(r.sample){const t=yield this.bucketer.isSampled(r.sample,{eventName:e,eventLevel:i,payload:o});if(!t.isSampled)return this.logger.debug("Event sample not matched",{eventName:e,matchedSample:t.matchedSample,bucketedNumber:t.bucketedNumber,bucketKey:t.bucketKey}),null}let a=o;r.transforms&&(a=yield this.transformer.applyAll(o,r.transforms,{eventName:e,eventLevel:i,payload:o})),yield this.effectsManager.dispatch({eventType:"event_tracked",name:e,value:a});const u=this.datafileReader.getDestinationNames();for(const t of u){const s=this.datafileReader.getDestination(t);if(!s)continue;if(!this.modulesManager.transportExists(s.transport)){this.logger.error("Destination has no transport",{eventName:e,destinationName:t});continue}let o=a;if(r.destinations&&void 0!==r.destinations[t]){const n=r.destinations[t];if(!1===n){this.logger.debug("Event has destination disabled",{eventName:e,destinationName:t});continue}if("object"==typeof n&&n.conditions){if(!(yield this.conditionsChecker.allAreMatched(n.conditions,{eventName:e,eventLevel:i,payload:o}))){this.logger.debug("Destination conditions not matched for event",{eventName:e,destinationName:t});continue}if(n.sample){const r=yield this.bucketer.isSampled(n.sample,{eventName:e,eventLevel:i,payload:o});if(!r.isSampled){this.logger.debug("Destination sample not matched for event",{eventName:e,destinationName:t,matchedSample:r.matchedSample,bucketedNumber:r.bucketedNumber,bucketKey:r.bucketKey});continue}}n.transforms&&(o=yield this.transformer.applyAll(a,n.transforms,{eventName:e,eventLevel:i,payload:o}))}}!s.conditions||(yield this.conditionsChecker.allAreMatched(s.conditions,{eventName:e,eventLevel:i,payload:a}))?!s.sample||(yield this.bucketer.isSampled(s.sample,{eventName:e,eventLevel:i,payload:o})).isSampled?(s.transforms&&(o=yield this.transformer.applyAll(o,s.transforms,{eventName:e,eventLevel:i,payload:o,destinationName:t,attributes:this.attributesManager.getAttributesMap()})),yield this.modulesManager.transport(s.transport,t,e,o,i,n)):this.logger.debug("Destination sample not matched",{eventName:e,destinationName:t}):this.logger.debug("Destination conditions not matched",{eventName:e,destinationName:t})}return a})}track(e,t){this.addToQueue({type:"track",name:e,value:t}),this.processQueue()}getStateValue(e){return this.effectsManager.getStateValue(e)}spawn(){}}function I(e={}){return new K(e)}export{f as AttributesManager,D as Bucketer,$ as BucketerOptions,r as DatafileReader,B as EffectsManager,a as Emitter,K as Eventvisor,s as Logger,P as MAX_BUCKETED_NUMBER,m as ModulesManager,E as MurmurHashV3,y as SourceResolver,j as Transformer,w as compareSegments,x as compareVersions,I as createInstance,o as createLogger,n as defaultLogHandler,e as emptyDatafile,T as getBucketedNumber,t as getComplexPersists,i as loggerPrefix,b as semver,A as validateAndParse};
2
2
  //# sourceMappingURL=index.mjs.map
package/dist/index.mjs.gz CHANGED
Binary file