trigger_system 1.1.8 → 1.2.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/node/node.js CHANGED
@@ -136,7 +136,7 @@ ${X.comment}`:X.comment}this.doc.range[2]=X.offset;break}default:this.errors.pus
136
136
  `)+1;while(X!==0)this.onNewLine(this.offset+X),X=this.source.indexOf(`
137
137
  `,X)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(U){let X=U.items[U.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,X.value){let q="end"in X.value?X.value.end:void 0;if((Array.isArray(q)?q[q.length-1]:void 0)?.type==="comment")q?.push(this.sourceToken);else U.items.push({start:[this.sourceToken]})}else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"space":case"comment":if(X.value)U.items.push({start:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else{if(this.atIndentedComment(X.start,U.indent)){let Z=U.items[U.items.length-2]?.value?.end;if(Array.isArray(Z)){Array.prototype.push.apply(Z,X.start),Z.push(this.sourceToken),U.items.pop();return}}X.start.push(this.sourceToken)}return}if(this.indent>=U.indent){let q=!this.onKeyLine&&this.indent===U.indent,Z=q&&(X.sep||X.explicitKey)&&this.type!=="seq-item-ind",Q=[];if(Z&&X.sep&&!X.value){let G=[];for(let Y=0;Y<X.sep.length;++Y){let J=X.sep[Y];switch(J.type){case"newline":G.push(Y);break;case"space":break;case"comment":if(J.indent>U.indent)G.length=0;break;default:G.length=0}}if(G.length>=2)Q=X.sep.splice(G[1])}switch(this.type){case"anchor":case"tag":if(Z||X.value)Q.push(this.sourceToken),U.items.push({start:Q}),this.onKeyLine=!0;else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"explicit-key-ind":if(!X.sep&&!X.explicitKey)X.start.push(this.sourceToken),X.explicitKey=!0;else if(Z||X.value)Q.push(this.sourceToken),U.items.push({start:Q,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(X.explicitKey)if(!X.sep)if(Q1(X.start,"newline"))Object.assign(X,{key:null,sep:[this.sourceToken]});else{let G=X2(X.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:null,sep:[this.sourceToken]}]})}else if(X.value)U.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Q1(X.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,key:null,sep:[this.sourceToken]}]});else if(hQ(X.key)&&!Q1(X.sep,"newline")){let G=X2(X.start),Y=X.key,J=X.sep;J.push(this.sourceToken),delete X.key,delete X.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:Y,sep:J}]})}else if(Q.length>0)X.sep=X.sep.concat(Q,this.sourceToken);else X.sep.push(this.sourceToken);else if(!X.sep)Object.assign(X,{key:null,sep:[this.sourceToken]});else if(X.value||Z)U.items.push({start:Q,key:null,sep:[this.sourceToken]});else if(Q1(X.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else X.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let G=this.flowScalar(this.type);if(Z||X.value)U.items.push({start:Q,key:G,sep:[]}),this.onKeyLine=!0;else if(X.sep)this.stack.push(G);else Object.assign(X,{key:G,sep:[]}),this.onKeyLine=!0;return}default:{let G=this.startBlockValue(U);if(G){if(G.type==="block-seq"){if(!X.explicitKey&&X.sep&&!Q1(X.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(q)U.items.push({start:Q});this.stack.push(G);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(U){let X=U.items[U.items.length-1];switch(this.type){case"newline":if(X.value){let q="end"in X.value?X.value.end:void 0;if((Array.isArray(q)?q[q.length-1]:void 0)?.type==="comment")q?.push(this.sourceToken);else U.items.push({start:[this.sourceToken]})}else X.start.push(this.sourceToken);return;case"space":case"comment":if(X.value)U.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(X.start,U.indent)){let Z=U.items[U.items.length-2]?.value?.end;if(Array.isArray(Z)){Array.prototype.push.apply(Z,X.start),Z.push(this.sourceToken),U.items.pop();return}}X.start.push(this.sourceToken)}return;case"anchor":case"tag":if(X.value||this.indent<=U.indent)break;X.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==U.indent)break;if(X.value||Q1(X.start,"seq-item-ind"))U.items.push({start:[this.sourceToken]});else X.start.push(this.sourceToken);return}if(this.indent>U.indent){let q=this.startBlockValue(U);if(q){this.stack.push(q);return}}yield*this.pop(),yield*this.step()}*flowCollection(U){let X=U.items[U.items.length-1];if(this.type==="flow-error-end"){let q;do yield*this.pop(),q=this.peek(1);while(q?.type==="flow-collection")}else if(U.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!X||X.sep)U.items.push({start:[this.sourceToken]});else X.start.push(this.sourceToken);return;case"map-value-ind":if(!X||X.value)U.items.push({start:[],key:null,sep:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else Object.assign(X,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!X||X.value)U.items.push({start:[this.sourceToken]});else if(X.sep)X.sep.push(this.sourceToken);else X.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Z=this.flowScalar(this.type);if(!X||X.value)U.items.push({start:[],key:Z,sep:[]});else if(X.sep)this.stack.push(Z);else Object.assign(X,{key:Z,sep:[]});return}case"flow-map-end":case"flow-seq-end":U.end.push(this.sourceToken);return}let q=this.startBlockValue(U);if(q)this.stack.push(q);else yield*this.pop(),yield*this.step()}else{let q=this.peek(2);if(q.type==="block-map"&&(this.type==="map-value-ind"&&q.indent===U.indent||this.type==="newline"&&!q.items[q.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&q.type!=="flow-collection"){let Z=C4(q),Q=X2(Z);vQ(U);let G=U.end.splice(1,U.end.length);G.push(this.sourceToken);let Y={type:"block-map",offset:U.offset,indent:U.indent,items:[{start:Q,key:U,sep:G}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}else yield*this.lineEnd(U)}}flowScalar(U){if(this.onNewLine){let X=this.source.indexOf(`
138
138
  `)+1;while(X!==0)this.onNewLine(this.offset+X),X=this.source.indexOf(`
139
- `,X)+1}return{type:U,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(U){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let X=C4(U),q=X2(X);return q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let X=C4(U),q=X2(X);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(U,X){if(this.type!=="comment")return!1;if(this.indent<=X)return!1;return U.every((q)=>q.type==="newline"||q.type==="space")}*documentEnd(U){if(this.type!=="doc-mode"){if(U.end)U.end.push(this.sourceToken);else U.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(U){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(U.end)U.end.push(this.sourceToken);else U.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}QA.Parser=xQ});var dQ=R((zA)=>{var uQ=nU(),YA=e2(),G6=U6(),JA=YU(),HA=k(),WA=YX(),mQ=JX();function pQ(U){let X=U.prettyErrors!==!1;return{lineCounter:U.lineCounter||X&&new WA.LineCounter||null,prettyErrors:X}}function _A(U,X={}){let{lineCounter:q,prettyErrors:Z}=pQ(X),Q=new mQ.Parser(q?.addNewLine),G=new uQ.Composer(X),Y=Array.from(G.compose(Q.parse(U)));if(Z&&q)for(let J of Y)J.errors.forEach(G6.prettifyError(U,q)),J.warnings.forEach(G6.prettifyError(U,q));if(Y.length>0)return Y;return Object.assign([],{empty:!0},G.streamInfo())}function lQ(U,X={}){let{lineCounter:q,prettyErrors:Z}=pQ(X),Q=new mQ.Parser(q?.addNewLine),G=new uQ.Composer(X),Y=null;for(let J of G.compose(Q.parse(U),!0,U.length))if(!Y)Y=J;else if(Y.options.logLevel!=="silent"){Y.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(Z&&q)Y.errors.forEach(G6.prettifyError(U,q)),Y.warnings.forEach(G6.prettifyError(U,q));return Y}function $A(U,X,q){let Z=void 0;if(typeof X==="function")Z=X;else if(q===void 0&&X&&typeof X==="object")q=X;let Q=lQ(U,q);if(!Q)return null;if(Q.warnings.forEach((G)=>JA.warn(Q.options.logLevel,G)),Q.errors.length>0)if(Q.options.logLevel!=="silent")throw Q.errors[0];else Q.errors=[];return Q.toJS(Object.assign({reviver:Z},q))}function LA(U,X,q){let Z=null;if(typeof X==="function"||Array.isArray(X))Z=X;else if(q===void 0&&X)q=X;if(typeof q==="string")q=q.length;if(typeof q==="number"){let Q=Math.round(q);q=Q<1?void 0:Q>8?{indent:8}:{indent:Q}}if(U===void 0){let{keepUndefined:Q}=q??X??{};if(!Q)return}if(HA.isDocument(U)&&!Z)return U.toString(q);return new YA.Document(U,Z,q).toString(q)}zA.parse=$A;zA.parseAllDocuments=_A;zA.parseDocument=lQ;zA.stringify=LA});var WX=R((EA)=>{var TA=nU(),VA=e2(),RA=gU(),HX=U6(),DA=h2(),G1=k(),MA=U1(),wA=i(),PA=q1(),IA=Z1(),KA=K4(),NA=GX(),CA=YX(),SA=JX(),S4=dQ(),cQ=k2();EA.Composer=TA.Composer;EA.Document=VA.Document;EA.Schema=RA.Schema;EA.YAMLError=HX.YAMLError;EA.YAMLParseError=HX.YAMLParseError;EA.YAMLWarning=HX.YAMLWarning;EA.Alias=DA.Alias;EA.isAlias=G1.isAlias;EA.isCollection=G1.isCollection;EA.isDocument=G1.isDocument;EA.isMap=G1.isMap;EA.isNode=G1.isNode;EA.isPair=G1.isPair;EA.isScalar=G1.isScalar;EA.isSeq=G1.isSeq;EA.Pair=MA.Pair;EA.Scalar=wA.Scalar;EA.YAMLMap=PA.YAMLMap;EA.YAMLSeq=IA.YAMLSeq;EA.CST=KA;EA.Lexer=NA.Lexer;EA.LineCounter=CA.LineCounter;EA.Parser=SA.Parser;EA.parse=S4.parse;EA.parseAllDocuments=S4.parseAllDocuments;EA.parseDocument=S4.parseDocument;EA.stringify=S4.stringify;EA.visit=cQ.visit;EA.visitAsync=cQ.visitAsync});class ZG{queue=[];engine;config;timer=null;isProcessing=!1;constructor(U,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=U,this.config=X}push(U){if(this.queue.push(U),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let U=this.queue.splice(0,this.config.maxBatchSize);if(U.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${U.length} events.`);for(let X of U)try{await this.engine.evaluateContext(X)}catch(q){console.error(`[EventQueue] Error processing event ${X.event}:`,q)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class QG{keyPrefix;cache=new Map;isLoaded=!1;constructor(U="trigger_system:"){this.keyPrefix=U}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let U=window.localStorage.getItem(this.keyPrefix+"state");if(U){let X=JSON.parse(U);this.cache=new Map(Object.entries(X))}}catch(U){console.error("[BrowserPersistence] Failed to load from localStorage:",U)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let U=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(U))}catch(U){console.error("[BrowserPersistence] Failed to save to localStorage:",U)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(U,X){this.ensureLoaded(),this.cache.set(U,X),this.persist()}async deleteState(U){this.ensureLoaded(),this.cache.delete(U),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y6{static getNestedValue(U,X){let q=U.split("."),Z=X;for(let Q of q){if(Z===null||Z===void 0)return;if(typeof Z==="object"&&Z!==null&&Q in Z)Z=Z[Q];else return}return Z}static interpolate(U,X){if(typeof U!=="string")return U;return U.replace(/\$\{([^}]+)\}/g,(q,Z)=>{let Q=this.getNestedValue(Z,X);if(Q!==void 0)return String(Q);return q})}static compare(U,X,q){switch(X){case"EQ":case"==":return U==q;case"NEQ":case"!=":return U!=q;case"GT":case">":return Number(U)>Number(q);case"GTE":case">=":return Number(U)>=Number(q);case"LT":case"<":return Number(U)<Number(q);case"LTE":case"<=":return Number(U)<=Number(q);case"IN":return Array.isArray(q)&&q.some((Z)=>Z===U);case"NOT_IN":return Array.isArray(q)&&!q.some((Z)=>Z===U);case"CONTAINS":if(Array.isArray(U)||typeof U==="string")return U.includes(q);return!1;case"NOT_CONTAINS":if(Array.isArray(U)||typeof U==="string")return!U.includes(q);return!1;case"STARTS_WITH":if(typeof U==="string"&&typeof q==="string")return U.startsWith(q);return!1;case"ENDS_WITH":if(typeof U==="string"&&typeof q==="string")return U.endsWith(q);return!1;case"IS_EMPTY":if(typeof U==="string")return U==="";if(Array.isArray(U))return U.length===0;if(U===null||U===void 0)return!0;if(typeof U==="object")return Object.keys(U).length===0;return!1;case"IS_NULL":case"IS_NONE":return U===null||U===void 0;case"HAS_KEY":if(typeof U==="object"&&U!==null&&typeof q==="string")return q in U;return!1;case"MATCHES":if(typeof q==="string")return new RegExp(q).test(String(U));return!1;case"RANGE":if(Array.isArray(q)&&q.length===2){let Z=Number(U),Q=Number(q[0]),G=Number(q[1]);return!isNaN(Z)&&!isNaN(Q)&&!isNaN(G)&&Z>=Q&&Z<=G}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var J6;((G)=>{G.ENGINE_START="engine:start";G.ENGINE_DONE="engine:done";G.RULE_MATCH="rule:match";G.ACTION_SUCCESS="action:success";G.ACTION_ERROR="action:error"})(J6||={});var VX;((Z)=>{Z.RULE_ADDED="rule:added";Z.RULE_REMOVED="rule:removed";Z.RULE_UPDATED="rule:updated"})(VX||={});var VO=J6,H6=VX;class f4{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new f4;return this.instance}on(U,X){let q=U;if(!this.handlers.has(q))this.handlers.set(q,new Set);return this.handlers.get(q).add(X),()=>this.off(q,X)}off(U,X){let q=U,Z=this.handlers.get(q);if(Z)Z.delete(X)}emit(U,X){let q=U,Z=this.handlers.get(q);if(Z)Z.forEach((Q)=>{try{Q(X)}catch(G){console.error(`Error in event handler for ${q}:`,G)}})}}var N0=f4.getInstance();class G2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(U=[]){if(Array.isArray(U))this._rules=U;else this._config=U,this._rules=[...U.rules];this.sortRules()}sortRules(){this._rules.sort((U,X)=>(X.priority||0)-(U.priority||0))}registerAction(U,X){this.actionHandlers.set(U,X)}async processEvent(U){let X=[];if(!U.state)U.state={};let q=this._rules.filter((Z)=>Z.enabled!==!1&&Z.on===U.event);for(let Z of q){if(Z.cooldown&&this.checkCooldown(Z.id,Z.cooldown))continue;if(this.evaluateConditions(Z.if,U)){let Q=await this.executeRuleActions(Z.do,U);if(this.lastExecution.set(Z.id,Date.now()),X.push({ruleId:Z.id,success:!0,executedActions:Q}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(U,X={},q={}){let Z={event:U,data:X,vars:q,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(Z)}updateRules(U){let X=this.getRules(),q=new Set(X.map((Y)=>Y.id)),Z=new Set(U.map((Y)=>Y.id)),Q=U.filter((Y)=>!q.has(Y.id)),G=X.filter((Y)=>!Z.has(Y.id));this.rules=[...U],this.sortRules(),Q.forEach((Y)=>{this.emitRuleEvent(H6.RULE_ADDED,{ruleId:Y.id,timestamp:Date.now()})}),G.forEach((Y)=>{this.emitRuleEvent(H6.RULE_REMOVED,{ruleId:Y.id,timestamp:Date.now()})}),this.emitRuleEvent(H6.RULE_UPDATED,{count:U.length,added:Q.length,removed:G.length,unchanged:U.length-Q.length,timestamp:Date.now()})}emitRuleEvent(U,X){try{if(N0)N0.emit(U,{...X,timestamp:Date.now()})}catch(q){console.warn(`Could not emit event ${U}:`,q)}}getRules(){return[...this.rules]}checkCooldown(U,X){let q=this.lastExecution.get(U);if(!q)return!1;return Date.now()-q<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(U,X){if(!U)return!0;if(Array.isArray(U))return U.every((q)=>this.evaluateSingleCondition(q,X));return this.evaluateSingleCondition(U,X)}evaluateSingleCondition(U,X){if("operator"in U&&"conditions"in U){let G=U;if(G.operator==="OR")return G.conditions.some((Y)=>this.evaluateSingleCondition(Y,X));else return G.conditions.every((Y)=>this.evaluateSingleCondition(Y,X))}let q=U,Z=e.evaluate(q.field,X),Q=q.value;if(typeof Q==="string"&&Q.includes("${"))Q=e.interpolate(Q,X);return Y6.compare(Z,q.operator,Q)}async executeRuleActions(U,X){let q=[],Z=[],Q="ALL";if(Array.isArray(U))Z=U;else if(U&&typeof U==="object"&&"mode"in U&&"actions"in U){let G=U;Q=G.mode,Z=G.actions}else Z=[U];if(Q==="EITHER"&&Z.length>0){let G=Z.reduce((H,W)=>H+(W.probability||1),0),Y=Math.random()*G,J;for(let H of Z){let W=H.probability||1;if(Y-=W,Y<=0){J=H;break}}if(!J&&Z.length>0)J=Z[Z.length-1];if(J)Z=[J];else Z=[]}for(let G of Z){let Y=await this.executeSingleAction(G,X);q.push(Y)}return q}async executeSingleAction(U,X){if(!U.type&&!U.run&&!U.break&&!U.continue){let G=["params","run","delay","probability","if","then","else","break","continue","mode","actions"],Y=Object.keys(U).filter((J)=>!G.includes(J));for(let J of Y){if(U.type=J,typeof U[J]==="string")U.params={...U.params,message:U[J],content:U[J]};else if(typeof U[J]==="object"&&U[J]!==null)U.params={...U.params,...U[J]};break}}if(U.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${U.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(G){return{type:"RUN",error:String(G),timestamp:Date.now()}}let q=U.probability;if(typeof q==="string"){let G=e.evaluate(q,X);q=typeof G==="number"?G:Number(G)}if(q!==void 0&&Math.random()>q)return{type:U.type||"skipped",timestamp:Date.now(),result:{skipped:"probability check failed"}};let Z=U.delay;if(typeof Z==="string"){let G=e.evaluate(Z,X);Z=typeof G==="number"?G:Number(G)}if(Z&&Z>0)await new Promise((G)=>setTimeout(G,Z));let Q=this.interpolateParams(U.params||{},X);try{let G;try{let{ActionRegistry:J}=await Promise.resolve().then(() => (Q2(),RX)),H=J.getInstance().get(U.type);if(H)G=(W)=>H({...U,params:W},X)}catch{G=this.actionHandlers.get(U.type)}let Y;if(G)Y=await G(Q,X);else{let J=`No handler registered for action type: ${U.type}`;console.warn(J),Y={warning:J}}return{type:U.type,result:Y,timestamp:Date.now()}}catch(G){return console.error(`Error executing action ${U.type}:`,G),{type:U.type,error:String(G),timestamp:Date.now()}}}interpolateParams(U,X){let q={};for(let[Z,Q]of Object.entries(U))if(typeof Q==="string")q[Z]=e.interpolate(Q,X);else if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q))q[Z]=this.interpolateDeep(Q,X);else q[Z]=Q;return q}interpolateDeep(U,X){if(typeof U==="string")return e.interpolate(U,X);if(Array.isArray(U))return U.map((q)=>this.interpolateDeep(q,X));if(typeof U==="object"&&U!==null){let q={};for(let Z in U)q[Z]=this.interpolateDeep(U[Z],X);return q}return U}get rules(){return[...this._rules]}get config(){return this._config}set rules(U){this._rules=[...U],this.sortRules()}}Q2();P1();class g4 extends G2{actionRegistry;stateManager;constructor(U){super(U);this.actionRegistry=I1.getInstance(),this.stateManager=U0.getInstance()}async processEvent(U){let X=[];if(U.state=this.stateManager.getLiveProxy(),this.config?.stateConfig)await this.stateManager.applyConfig(this.config.stateConfig);if(N0.emit("engine:start",{context:U,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${U.event}`);let q=this.rules.filter((Z)=>Z.enabled!==!1&&Z.on===U.event);for(let Z of q){if(Z.cooldown&&this.checkCooldown(Z.id,Z.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${Z.id} in cooldown`);continue}if(this.evaluateConditions(Z.if,U)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${Z.name||Z.id}`);N0.emit("rule:match",{rule:Z,context:U});let G=await this.executeRuleActionsWithRegistry(Z.do,U);if(X.push({ruleId:Z.id,executedActions:G,success:!0}),this.updateLastExecution(Z.id),!this.shouldEvaluateAll())break}}return N0.emit("engine:done",{results:X,context:U}),X}async processEventSimple(U,X={},q={}){let Z={event:U,data:X,vars:q,timestamp:Date.now(),state:this.stateManager.getLiveProxy()};return this.processEvent(Z)}async executeRuleActionsWithRegistry(U,X){let q=[],Z=[],Q="ALL";if(Array.isArray(U))Z=U;else if(this.isActionGroup(U)){let G=U;Q=G.mode,Z=G.actions}else Z=[U];if(Q==="EITHER"&&Z.length>0){let G=Z.reduce((H,W)=>H+(W.probability||1),0),Y=Math.random()*G,J;for(let H of Z){let W=H.probability||1;if(Y-=W,Y<=0){J=H;break}}if(J)Z=[J]}for(let G of Z){let Y=await this.executeSingleActionWithRegistry(G,X);q.push(Y)}return q}isActionGroup(U){return typeof U==="object"&&U!==null&&"mode"in U&&"actions"in U}async executeSingleActionWithRegistry(U,X){if(!U.type&&!U.run&&!U.break&&!U.continue){let G=Object.keys(U);for(let Y of G)if(this.actionRegistry.get(Y)){if(U.type=Y,typeof U[Y]==="string")U.params={...U.params,message:U[Y],content:U[Y]};else if(typeof U[Y]==="object"&&U[Y]!==null)U.params={...U.params,...U[Y]};break}}if(U.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${U.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(G){return{type:"RUN",error:String(G),timestamp:Date.now()}}let q=U.probability;if(typeof q==="string"){let{ExpressionEngine:G}=OX(j4),Y=G.evaluate(q,X);q=typeof Y==="number"?Y:Number(Y)}if(q!==void 0&&Math.random()>q)return{type:U.type||"unknown",timestamp:Date.now(),result:{skipped:"probability check failed"}};if(U.break)return{type:"BREAK",result:"Break action",timestamp:Date.now()};if(U.continue)return{type:"CONTINUE",result:"Continue action",timestamp:Date.now()};let Z=U.delay;if(typeof Z==="string"){let{ExpressionEngine:G}=OX(j4),Y=G.evaluate(Z,X);Z=typeof Y==="number"?Y:Number(Y)}if(Z&&Z>0)await new Promise((G)=>setTimeout(G,Z));let Q=this.interpolateParams(U.params||{},X);try{let G=this.actionRegistry.get(U.type),Y;if(G)Y=await G({...U,params:Q},X);else{let J=`Generic or unknown action type: ${U.type}`;if(this.config?.globalSettings?.strictActions)throw Error(J);console.warn(J),Y={warning:`Generic action executed: ${U.type}`}}return N0.emit("action:success",{action:{...U,params:Q},context:X,result:Y}),{type:U.type,result:Y,timestamp:Date.now()}}catch(G){return console.error("Error executing action:",U,G),N0.emit("action:error",{action:U,context:X,error:String(G)}),{type:U.type,error:String(G),timestamp:Date.now()}}}updateLastExecution(U){this.lastExecution.set(U,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(U,X){return this.executeRuleActionsWithRegistry(U,X)}async executeSingleAction(U,X){return this.executeSingleActionWithRegistry(U,X)}}Q2();P1();class GG{static create(U,X,q={}){return{event:U,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},vars:q,state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromRequest(U,X,q={}){let Z=new URL(U.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:U.method,path:Z.pathname,query:Object.fromEntries(Z.searchParams),headers:(()=>{let Q={};return U.headers.forEach((G,Y)=>Q[Y]=G),Q})(),body:X||{}},vars:{...q,ip:U.headers.get("x-forwarded-for")||"unknown"},state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromWebhook(U,X,q,Z={}){return{event:`WEBHOOK_${U.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:q,vars:{...Z,provider:U},state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(U)=>{try{return typeof U==="string"?JSON.parse(U):null}catch{return null}},jsonStringify:(U)=>{try{return JSON.stringify(U)}catch{return null}}}}}P1();Q2();P1();var l0=(U)=>Array.isArray(U)?U:[U],DX=(U,X)=>{let q=[[],[]];for(let Z of U)if(X(Z))q[0].push(Z);else q[1].push(Z);return q},W6=Array,F0=(U,X)=>U.includes(X),MX=(U,X=0)=>[...Array(U)].map((q,Z)=>Z+X),g=(U,X,q)=>{if(U===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(q?.prepend)if(Array.isArray(X))U.unshift(...X);else U.unshift(X);else if(Array.isArray(X))U.push(...X);else U.push(X);return U},g0=(U,X)=>{if(X===void 0||X===null)return U??[];if(U===void 0||U===null)return l0(X);return U.concat(X)},wX=(...U)=>U.reduce(g0,[]),C0=(U,X,q)=>{if(U===void 0)return Array.isArray(X)?X:[X];let Z=q?.isEqual??((Q,G)=>Q===G);for(let Q of l0(X))if(!U.some((G)=>Z(G,Q)))U.push(Q);return U},PX=(U,X)=>U.reduce((q,Z)=>{let Q=Z[X];return q[Q]=g(q[Q],Z),q},{}),y0=(U,X,q)=>U.length===X.length&&U.every(q?.isEqual?(Z,Q)=>q.isEqual(Z,X[Q]):(Z,Q)=>Z===X[Q]);var G0=(U,X)=>r(U)===X,r=(U)=>{let X=typeof U;return X==="object"?U===null?"null":"object":X==="function"?"object":X},Y0={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},IX={...Y0,function:"a function"};class KX extends Error{}var y=(U)=>Y1(U,KX),Y1=(U,X=Error)=>{throw new X(U)};class Y2 extends Error{name="ParseError"}var F=(U)=>Y1(U,Y2),D0=(U)=>` ${U}`,NX="​";var S=(U,X)=>{let q={},Z=Array.isArray(U),Q=!1;for(let[G,Y]of Object.entries(U).entries()){let J=Z?X(G,Y[1]):X(...Y,G);Q||=typeof J[0]==="number";let H=Array.isArray(J[0])||J.length===0?J:[J];for(let[W,$]of H)if(typeof W==="object")q[W.group]=g(q[W.group],$);else q[W]=$}return Q?Object.values(q):q};var y4=Object.entries;var n=(U,X)=>(U in X),K1=(U,X)=>(X in U);class k4{constructor(U){Object.assign(this,U)}}var CX=class{};class J2 extends CX{}var YG=(U,X)=>{let q={},Z={},Q;for(Q in U)if(Q in X)q[Q]=U[Q];else Z[Q]=U[Q];return[q,Z]};var _6=(U,X)=>YG(U,X)[1],S0=(U)=>Object.keys(U).length===0,J1=(U)=>[...Object.entries(U),...Object.getOwnPropertySymbols(U).map((X)=>[X,U[X]])],SX=(U,X)=>Object.defineProperties(U,Object.getOwnPropertyDescriptors(X)),EX=(U)=>{let X=Object.keys(U).sort(),q={};for(let Z=0;Z<X.length;Z++)q[X[Z]]=U[X[Z]];return q};var J0=D0(`unset${NX}`),jX=(U)=>Object.values(U).filter((X)=>{if(typeof X==="number")return!0;return typeof U[X]!=="number"});var v4={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},h4=globalThis.File??Blob,x4={ArrayBuffer,Blob,File:h4,FormData,Headers,Request,Response,URL},JG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},H1={...v4,...x4,...JG,String,Number,Boolean},H2=(U)=>{let X=Object.getPrototypeOf(U);while(X?.constructor&&(!n(X.constructor.name,H1)||!(U instanceof H1[X.constructor.name])))X=Object.getPrototypeOf(X);let q=X?.constructor?.name;if(q===void 0||q==="Object")return;return q},W2=(U)=>typeof U==="object"&&U!==null?H2(U)??"object":r(U);var h=Array.isArray,HG={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},WG={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},_G={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},bX={...HG,...WG,..._G},_2=(U)=>{let X=Object(U).name??null;return X&&n(X,H1)&&H1[X]===U?X:null};var u4=(U,X)=>{let q=U.prototype;while(q!==null){if(q===X.prototype)return!0;q=Object.getPrototypeOf(q)}return!1};var fX=(U)=>gX(U,new Map),gX=(U,X)=>{if(typeof U!=="object"||U===null)return U;if(X?.has(U))return X.get(U);let q=_2(U.constructor);if(q==="Date")return new Date(U.getTime());if(q&&q!=="Array")return U;let Z=Array.isArray(U)?U.slice():Object.create(Object.getPrototypeOf(U)),Q=Object.getOwnPropertyDescriptors(U);if(X){X.set(U,Z);for(let G in Q){let Y=Q[G];if("get"in Y||"set"in Y)continue;Y.value=gX(Y.value,X)}}return Object.defineProperties(Z,Q),Z};var $G=(U)=>{let X=J0;return()=>X===J0?X=U():X},d0=(U)=>typeof U==="function"&&U.length===0;var yX=class extends Function{constructor(...U){let X=U.slice(0,-1),q=U[U.length-1];try{super(...X,q)}catch(Z){return y(`Encountered an unexpected error while compiling your definition:
139
+ `,X)+1}return{type:U,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(U){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let X=C4(U),q=X2(X);return q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let X=C4(U),q=X2(X);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(U,X){if(this.type!=="comment")return!1;if(this.indent<=X)return!1;return U.every((q)=>q.type==="newline"||q.type==="space")}*documentEnd(U){if(this.type!=="doc-mode"){if(U.end)U.end.push(this.sourceToken);else U.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(U){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(U.end)U.end.push(this.sourceToken);else U.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}QA.Parser=xQ});var dQ=R((zA)=>{var uQ=nU(),YA=e2(),G6=U6(),JA=YU(),HA=k(),WA=YX(),mQ=JX();function pQ(U){let X=U.prettyErrors!==!1;return{lineCounter:U.lineCounter||X&&new WA.LineCounter||null,prettyErrors:X}}function _A(U,X={}){let{lineCounter:q,prettyErrors:Z}=pQ(X),Q=new mQ.Parser(q?.addNewLine),G=new uQ.Composer(X),Y=Array.from(G.compose(Q.parse(U)));if(Z&&q)for(let J of Y)J.errors.forEach(G6.prettifyError(U,q)),J.warnings.forEach(G6.prettifyError(U,q));if(Y.length>0)return Y;return Object.assign([],{empty:!0},G.streamInfo())}function lQ(U,X={}){let{lineCounter:q,prettyErrors:Z}=pQ(X),Q=new mQ.Parser(q?.addNewLine),G=new uQ.Composer(X),Y=null;for(let J of G.compose(Q.parse(U),!0,U.length))if(!Y)Y=J;else if(Y.options.logLevel!=="silent"){Y.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(Z&&q)Y.errors.forEach(G6.prettifyError(U,q)),Y.warnings.forEach(G6.prettifyError(U,q));return Y}function $A(U,X,q){let Z=void 0;if(typeof X==="function")Z=X;else if(q===void 0&&X&&typeof X==="object")q=X;let Q=lQ(U,q);if(!Q)return null;if(Q.warnings.forEach((G)=>JA.warn(Q.options.logLevel,G)),Q.errors.length>0)if(Q.options.logLevel!=="silent")throw Q.errors[0];else Q.errors=[];return Q.toJS(Object.assign({reviver:Z},q))}function LA(U,X,q){let Z=null;if(typeof X==="function"||Array.isArray(X))Z=X;else if(q===void 0&&X)q=X;if(typeof q==="string")q=q.length;if(typeof q==="number"){let Q=Math.round(q);q=Q<1?void 0:Q>8?{indent:8}:{indent:Q}}if(U===void 0){let{keepUndefined:Q}=q??X??{};if(!Q)return}if(HA.isDocument(U)&&!Z)return U.toString(q);return new YA.Document(U,Z,q).toString(q)}zA.parse=$A;zA.parseAllDocuments=_A;zA.parseDocument=lQ;zA.stringify=LA});var WX=R((EA)=>{var TA=nU(),VA=e2(),RA=gU(),HX=U6(),DA=h2(),G1=k(),MA=U1(),wA=i(),PA=q1(),IA=Z1(),KA=K4(),NA=GX(),CA=YX(),SA=JX(),S4=dQ(),cQ=k2();EA.Composer=TA.Composer;EA.Document=VA.Document;EA.Schema=RA.Schema;EA.YAMLError=HX.YAMLError;EA.YAMLParseError=HX.YAMLParseError;EA.YAMLWarning=HX.YAMLWarning;EA.Alias=DA.Alias;EA.isAlias=G1.isAlias;EA.isCollection=G1.isCollection;EA.isDocument=G1.isDocument;EA.isMap=G1.isMap;EA.isNode=G1.isNode;EA.isPair=G1.isPair;EA.isScalar=G1.isScalar;EA.isSeq=G1.isSeq;EA.Pair=MA.Pair;EA.Scalar=wA.Scalar;EA.YAMLMap=PA.YAMLMap;EA.YAMLSeq=IA.YAMLSeq;EA.CST=KA;EA.Lexer=NA.Lexer;EA.LineCounter=CA.LineCounter;EA.Parser=SA.Parser;EA.parse=S4.parse;EA.parseAllDocuments=S4.parseAllDocuments;EA.parseDocument=S4.parseDocument;EA.stringify=S4.stringify;EA.visit=cQ.visit;EA.visitAsync=cQ.visitAsync});class ZG{queue=[];engine;config;timer=null;isProcessing=!1;constructor(U,X={maxBatchSize:10,flushIntervalMs:100}){this.engine=U,this.config=X}push(U){if(this.queue.push(U),this.queue.length>=this.config.maxBatchSize)this.processQueue();else if(!this.timer)this.timer=setTimeout(()=>this.processQueue(),this.config.flushIntervalMs)}async processQueue(){if(this.isProcessing)return;if(this.isProcessing=!0,this.timer)clearTimeout(this.timer),this.timer=null;let U=this.queue.splice(0,this.config.maxBatchSize);if(U.length===0){this.isProcessing=!1;return}console.debug(`[EventQueue] Processing batch of ${U.length} events.`);for(let X of U)try{await this.engine.evaluateContext(X)}catch(q){console.error(`[EventQueue] Error processing event ${X.event}:`,q)}if(this.queue.length>0)setTimeout(()=>this.processQueue(),0);this.isProcessing=!1}getQueueLength(){return this.queue.length}}class QG{keyPrefix;cache=new Map;isLoaded=!1;constructor(U="trigger_system:"){this.keyPrefix=U}isAvailable(){return typeof window<"u"&&typeof window.localStorage<"u"}ensureLoaded(){if(this.isLoaded)return;if(this.isAvailable())try{let U=window.localStorage.getItem(this.keyPrefix+"state");if(U){let X=JSON.parse(U);this.cache=new Map(Object.entries(X))}}catch(U){console.error("[BrowserPersistence] Failed to load from localStorage:",U)}this.isLoaded=!0}persist(){if(this.isAvailable())try{let U=Object.fromEntries(this.cache);window.localStorage.setItem(this.keyPrefix+"state",JSON.stringify(U))}catch(U){console.error("[BrowserPersistence] Failed to save to localStorage:",U)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(U,X){this.ensureLoaded(),this.cache.set(U,X),this.persist()}async deleteState(U){this.ensureLoaded(),this.cache.delete(U),this.persist()}async clearState(){this.cache.clear(),this.persist()}}class Y6{static getNestedValue(U,X){let q=U.split("."),Z=X;for(let Q of q){if(Z===null||Z===void 0)return;if(typeof Z==="object"&&Z!==null&&Q in Z)Z=Z[Q];else return}return Z}static interpolate(U,X){if(typeof U!=="string")return U;return U.replace(/\$\{([^}]+)\}/g,(q,Z)=>{let Q=this.getNestedValue(Z,X);if(Q!==void 0)return String(Q);return q})}static compare(U,X,q){switch(X){case"EQ":case"==":return U==q;case"NEQ":case"!=":return U!=q;case"GT":case">":return Number(U)>Number(q);case"GTE":case">=":return Number(U)>=Number(q);case"LT":case"<":return Number(U)<Number(q);case"LTE":case"<=":return Number(U)<=Number(q);case"IN":return Array.isArray(q)&&q.some((Z)=>Z===U);case"NOT_IN":return Array.isArray(q)&&!q.some((Z)=>Z===U);case"CONTAINS":if(Array.isArray(U)||typeof U==="string")return U.includes(q);return!1;case"NOT_CONTAINS":if(Array.isArray(U)||typeof U==="string")return!U.includes(q);return!1;case"STARTS_WITH":if(typeof U==="string"&&typeof q==="string")return U.startsWith(q);return!1;case"ENDS_WITH":if(typeof U==="string"&&typeof q==="string")return U.endsWith(q);return!1;case"IS_EMPTY":if(typeof U==="string")return U==="";if(Array.isArray(U))return U.length===0;if(U===null||U===void 0)return!0;if(typeof U==="object")return Object.keys(U).length===0;return!1;case"IS_NULL":case"IS_NONE":return U===null||U===void 0;case"HAS_KEY":if(typeof U==="object"&&U!==null&&typeof q==="string")return q in U;return!1;case"MATCHES":if(typeof q==="string")return new RegExp(q).test(String(U));return!1;case"RANGE":if(Array.isArray(q)&&q.length===2){let Z=Number(U),Q=Number(q[0]),G=Number(q[1]);return!isNaN(Z)&&!isNaN(Q)&&!isNaN(G)&&Z>=Q&&Z<=G}return!1;default:return console.warn(`Unknown operator: ${X}`),!1}}}var J6;((G)=>{G.ENGINE_START="engine:start";G.ENGINE_DONE="engine:done";G.RULE_MATCH="rule:match";G.ACTION_SUCCESS="action:success";G.ACTION_ERROR="action:error"})(J6||={});var VX;((Z)=>{Z.RULE_ADDED="rule:added";Z.RULE_REMOVED="rule:removed";Z.RULE_UPDATED="rule:updated"})(VX||={});var VO=J6,H6=VX;class f4{static instance;handlers=new Map;constructor(){}static getInstance(){if(!this.instance)this.instance=new f4;return this.instance}on(U,X){let q=U;if(!this.handlers.has(q))this.handlers.set(q,new Set);return this.handlers.get(q).add(X),()=>this.off(q,X)}off(U,X){let q=U,Z=this.handlers.get(q);if(Z)Z.delete(X)}emit(U,X){let q=U,Z=this.handlers.get(q);if(Z)Z.forEach((Q)=>{try{Q(X)}catch(G){console.error(`Error in event handler for ${q}:`,G)}})}}var N0=f4.getInstance();class G2{_rules=[];actionHandlers=new Map;lastExecution=new Map;_config;constructor(U=[]){if(Array.isArray(U))this._rules=U;else this._config=U,this._rules=[...U.rules];this.sortRules()}sortRules(){this._rules.sort((U,X)=>(X.priority||0)-(U.priority||0))}registerAction(U,X){this.actionHandlers.set(U,X)}async processEvent(U){let X=[];if(!U.state)U.state={};let q=this._rules.filter((Z)=>Z.enabled!==!1&&Z.on===U.event);for(let Z of q){if(Z.cooldown&&this.checkCooldown(Z.id,Z.cooldown))continue;if(this.evaluateConditions(Z.if,U)){let Q=await this.executeRuleActions(Z.do,U);if(this.lastExecution.set(Z.id,Date.now()),X.push({ruleId:Z.id,success:!0,executedActions:Q}),!this.shouldEvaluateAll())break}}return X}async processEventSimple(U,X={},q={}){let Z={event:U,data:X,vars:q,timestamp:Date.now(),state:this.getStateContext?this.getStateContext():{}};return this.processEvent(Z)}updateRules(U){let X=this.getRules(),q=new Set(X.map((Y)=>Y.id)),Z=new Set(U.map((Y)=>Y.id)),Q=U.filter((Y)=>!q.has(Y.id)),G=X.filter((Y)=>!Z.has(Y.id));this.rules=[...U],this.sortRules(),Q.forEach((Y)=>{this.emitRuleEvent(H6.RULE_ADDED,{ruleId:Y.id,timestamp:Date.now()})}),G.forEach((Y)=>{this.emitRuleEvent(H6.RULE_REMOVED,{ruleId:Y.id,timestamp:Date.now()})}),this.emitRuleEvent(H6.RULE_UPDATED,{count:U.length,added:Q.length,removed:G.length,unchanged:U.length-Q.length,timestamp:Date.now()})}emitRuleEvent(U,X){try{if(N0)N0.emit(U,{...X,timestamp:Date.now()})}catch(q){console.warn(`Could not emit event ${U}:`,q)}}getRules(){return[...this.rules]}checkCooldown(U,X){let q=this.lastExecution.get(U);if(!q)return!1;return Date.now()-q<X}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}getStateContext(){return{}}evaluateConditions(U,X){if(!U)return!0;if(Array.isArray(U))return U.every((q)=>this.evaluateSingleCondition(q,X));return this.evaluateSingleCondition(U,X)}evaluateSingleCondition(U,X){if("operator"in U&&"conditions"in U){let G=U;if(G.operator==="OR")return G.conditions.some((Y)=>this.evaluateSingleCondition(Y,X));else return G.conditions.every((Y)=>this.evaluateSingleCondition(Y,X))}let q=U,Z=e.evaluate(q.field,X),Q=q.value;if(typeof Q==="string"&&Q.includes("${"))Q=e.interpolate(Q,X);return Y6.compare(Z,q.operator,Q)}async executeRuleActions(U,X){let q=[],Z=[],Q="ALL";if(Array.isArray(U))Z=U;else if(U&&typeof U==="object"&&"mode"in U&&"actions"in U){let Y=U;Q=Y.mode,Z=Y.actions}else Z=[U];if(Q==="EITHER"&&Z.length>0){let Y=Z.reduce((W,$)=>W+($.probability||1),0),J=Math.random()*Y,H;for(let W of Z){let $=W.probability||1;if(J-=$,J<=0){H=W;break}}if(!H&&Z.length>0)H=Z[Z.length-1];if(H)Z=[H];else Z=[]}let G=!1;for(let Y of Z){if(G)break;if("if"in Y&&Y.if&&(Y.then||Y.else)){let H=this.evaluateConditions(Y.if,X);if(H&&Y.then){let W=await this.executeRuleActions(Y.then,X);q.push(...W)}else if(!H&&Y.else){let W=await this.executeRuleActions(Y.else,X);q.push(...W)}continue}if("if"in Y&&Y.if){if(!this.evaluateConditions(Y.if,X))continue}if(Y.break){G=!0,q.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(Y.continue){q.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleAction(Y,X);q.push(J)}return q}async executeSingleAction(U,X){if(!U.type&&!U.run&&!U.break&&!U.continue){let G=["params","run","delay","probability","if","then","else","break","continue","mode","actions"],Y=Object.keys(U).filter((J)=>!G.includes(J));for(let J of Y){if(U.type=J,typeof U[J]==="string")U.params={...U.params,message:U[J],content:U[J]};else if(typeof U[J]==="object"&&U[J]!==null)U.params={...U.params,...U[J]};break}}if(U.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${U.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(G){return{type:"RUN",error:String(G),timestamp:Date.now()}}let q=U.probability;if(typeof q==="string"){let G=e.evaluate(q,X);q=typeof G==="number"?G:Number(G)}if(q!==void 0&&Math.random()>q)return{type:U.type||"skipped",timestamp:Date.now(),result:{skipped:"probability check failed"}};let Z=U.delay;if(typeof Z==="string"){let G=e.evaluate(Z,X);Z=typeof G==="number"?G:Number(G)}if(Z&&Z>0)await new Promise((G)=>setTimeout(G,Z));let Q=this.interpolateParams(U.params||{},X);try{let G;try{let{ActionRegistry:J}=await Promise.resolve().then(() => (Q2(),RX)),H=J.getInstance().get(U.type);if(H)G=(W)=>H({...U,params:W},X)}catch{G=this.actionHandlers.get(U.type)}let Y;if(G)Y=await G(Q,X);else{let J=`No handler registered for action type: ${U.type}`;console.warn(J),Y={warning:J}}return{type:U.type,result:Y,timestamp:Date.now()}}catch(G){return console.error(`Error executing action ${U.type}:`,G),{type:U.type,error:String(G),timestamp:Date.now()}}}interpolateParams(U,X){let q={};for(let[Z,Q]of Object.entries(U))if(typeof Q==="string")q[Z]=e.interpolate(Q,X);else if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q))q[Z]=this.interpolateDeep(Q,X);else q[Z]=Q;return q}interpolateDeep(U,X){if(typeof U==="string")return e.interpolate(U,X);if(Array.isArray(U))return U.map((q)=>this.interpolateDeep(q,X));if(typeof U==="object"&&U!==null){let q={};for(let Z in U)q[Z]=this.interpolateDeep(U[Z],X);return q}return U}get rules(){return[...this._rules]}get config(){return this._config}set rules(U){this._rules=[...U],this.sortRules()}}Q2();P1();class g4 extends G2{actionRegistry;stateManager;constructor(U){super(U);this.actionRegistry=I1.getInstance(),this.stateManager=U0.getInstance()}async processEvent(U){let X=[];if(U.state=this.stateManager.getLiveProxy(),this.config?.stateConfig)await this.stateManager.applyConfig(this.config.stateConfig);if(N0.emit("engine:start",{context:U,rulesCount:this.rules.length}),this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Evaluating context with ${this.rules.length} rules for event: ${U.event}`);let q=this.rules.filter((Z)=>Z.enabled!==!1&&Z.on===U.event);for(let Z of q){if(Z.cooldown&&this.checkCooldown(Z.id,Z.cooldown)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Rule ${Z.id} in cooldown`);continue}if(this.evaluateConditions(Z.if,U)){if(this.config?.globalSettings?.debugMode)console.log(`[RuleEngine] Executing rule: ${Z.name||Z.id}`);N0.emit("rule:match",{rule:Z,context:U});let G=await this.executeRuleActionsWithRegistry(Z.do,U);if(X.push({ruleId:Z.id,executedActions:G,success:!0}),this.updateLastExecution(Z.id),!this.shouldEvaluateAll())break}}return N0.emit("engine:done",{results:X,context:U}),X}async processEventSimple(U,X={},q={}){let Z={event:U,data:X,vars:q,timestamp:Date.now(),state:this.stateManager.getLiveProxy()};return this.processEvent(Z)}async executeRuleActionsWithRegistry(U,X){let q=[],Z=[],Q="ALL";if(Array.isArray(U))Z=U;else if(this.isActionGroup(U)){let Y=U;Q=Y.mode,Z=Y.actions}else Z=[U];if(Q==="EITHER"&&Z.length>0){let Y=Z.reduce((W,$)=>W+($.probability||1),0),J=Math.random()*Y,H;for(let W of Z){let $=W.probability||1;if(J-=$,J<=0){H=W;break}}if(H)Z=[H]}let G=!1;for(let Y of Z){if(G)break;if("if"in Y&&Y.if&&(Y.then||Y.else)){let H=this.evaluateConditions(Y.if,X);if(H&&Y.then){let W=await this.executeRuleActionsWithRegistry(Y.then,X);q.push(...W)}else if(!H&&Y.else){let W=await this.executeRuleActionsWithRegistry(Y.else,X);q.push(...W)}continue}if("if"in Y&&Y.if){if(!this.evaluateConditions(Y.if,X))continue}if(Y.break){G=!0,q.push({type:"BREAK",result:"Breaking action execution",timestamp:Date.now()});break}if(Y.continue){q.push({type:"CONTINUE",result:"Skipping remaining actions",timestamp:Date.now()});continue}let J=await this.executeSingleActionWithRegistry(Y,X);q.push(J)}return q}isActionGroup(U){return typeof U==="object"&&U!==null&&"mode"in U&&"actions"in U}async executeSingleActionWithRegistry(U,X){if(!U.type&&!U.run&&!U.break&&!U.continue){let G=Object.keys(U);for(let Y of G)if(this.actionRegistry.get(Y)){if(U.type=Y,typeof U[Y]==="string")U.params={...U.params,message:U[Y],content:U[Y]};else if(typeof U[Y]==="object"&&U[Y]!==null)U.params={...U.params,...U[Y]};break}}if(U.run)try{return{type:"RUN",result:Function("context","state","data","vars","env","helpers",`with(context) { ${U.run} }`)(X,X.state,X.data,X.vars,X.env,X.helpers),timestamp:Date.now()}}catch(G){return{type:"RUN",error:String(G),timestamp:Date.now()}}let q=U.probability;if(typeof q==="string"){let{ExpressionEngine:G}=OX(j4),Y=G.evaluate(q,X);q=typeof Y==="number"?Y:Number(Y)}if(q!==void 0&&Math.random()>q)return{type:U.type||"unknown",timestamp:Date.now(),result:{skipped:"probability check failed"}};if(U.break)return{type:"BREAK",result:"Break action",timestamp:Date.now()};if(U.continue)return{type:"CONTINUE",result:"Continue action",timestamp:Date.now()};let Z=U.delay;if(typeof Z==="string"){let{ExpressionEngine:G}=OX(j4),Y=G.evaluate(Z,X);Z=typeof Y==="number"?Y:Number(Y)}if(Z&&Z>0)await new Promise((G)=>setTimeout(G,Z));let Q=this.interpolateParams(U.params||{},X);try{let G=this.actionRegistry.get(U.type),Y;if(G)Y=await G({...U,params:Q},X);else{let J=`Generic or unknown action type: ${U.type}`;if(this.config?.globalSettings?.strictActions)throw Error(J);console.warn(J),Y={warning:`Generic action executed: ${U.type}`}}return N0.emit("action:success",{action:{...U,params:Q},context:X,result:Y}),{type:U.type,result:Y,timestamp:Date.now()}}catch(G){return console.error("Error executing action:",U,G),N0.emit("action:error",{action:U,context:X,error:String(G)}),{type:U.type,error:String(G),timestamp:Date.now()}}}updateLastExecution(U){this.lastExecution.set(U,Date.now())}getStateContext(){return this.stateManager.getAll()}shouldEvaluateAll(){return this.config?.globalSettings?.evaluateAll??!0}async executeRuleActions(U,X){return this.executeRuleActionsWithRegistry(U,X)}async executeSingleAction(U,X){return this.executeSingleActionWithRegistry(U,X)}}Q2();P1();class GG{static create(U,X,q={}){return{event:U,timestamp:Date.now(),data:typeof X==="object"&&X!==null?X:{value:X},vars:q,state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromRequest(U,X,q={}){let Z=new URL(U.url);return{event:"HTTP_REQUEST",timestamp:Date.now(),data:{method:U.method,path:Z.pathname,query:Object.fromEntries(Z.searchParams),headers:(()=>{let Q={};return U.headers.forEach((G,Y)=>Q[Y]=G),Q})(),body:X||{}},vars:{...q,ip:U.headers.get("x-forwarded-for")||"unknown"},state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static fromWebhook(U,X,q,Z={}){return{event:`WEBHOOK_${U.toUpperCase()}_${X.toUpperCase()}`,timestamp:Date.now(),data:q,vars:{...Z,provider:U},state:U0.getInstance().getLiveProxy(),helpers:this.getDefaultHelpers()}}static getDefaultHelpers(){return{now:()=>Date.now(),uuid:()=>crypto.randomUUID(),jsonParse:(U)=>{try{return typeof U==="string"?JSON.parse(U):null}catch{return null}},jsonStringify:(U)=>{try{return JSON.stringify(U)}catch{return null}}}}}P1();Q2();P1();var l0=(U)=>Array.isArray(U)?U:[U],DX=(U,X)=>{let q=[[],[]];for(let Z of U)if(X(Z))q[0].push(Z);else q[1].push(Z);return q},W6=Array,F0=(U,X)=>U.includes(X),MX=(U,X=0)=>[...Array(U)].map((q,Z)=>Z+X),g=(U,X,q)=>{if(U===void 0)return X===void 0?[]:Array.isArray(X)?X:[X];if(q?.prepend)if(Array.isArray(X))U.unshift(...X);else U.unshift(X);else if(Array.isArray(X))U.push(...X);else U.push(X);return U},g0=(U,X)=>{if(X===void 0||X===null)return U??[];if(U===void 0||U===null)return l0(X);return U.concat(X)},wX=(...U)=>U.reduce(g0,[]),C0=(U,X,q)=>{if(U===void 0)return Array.isArray(X)?X:[X];let Z=q?.isEqual??((Q,G)=>Q===G);for(let Q of l0(X))if(!U.some((G)=>Z(G,Q)))U.push(Q);return U},PX=(U,X)=>U.reduce((q,Z)=>{let Q=Z[X];return q[Q]=g(q[Q],Z),q},{}),y0=(U,X,q)=>U.length===X.length&&U.every(q?.isEqual?(Z,Q)=>q.isEqual(Z,X[Q]):(Z,Q)=>Z===X[Q]);var G0=(U,X)=>r(U)===X,r=(U)=>{let X=typeof U;return X==="object"?U===null?"null":"object":X==="function"?"object":X},Y0={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},IX={...Y0,function:"a function"};class KX extends Error{}var y=(U)=>Y1(U,KX),Y1=(U,X=Error)=>{throw new X(U)};class Y2 extends Error{name="ParseError"}var F=(U)=>Y1(U,Y2),D0=(U)=>` ${U}`,NX="​";var S=(U,X)=>{let q={},Z=Array.isArray(U),Q=!1;for(let[G,Y]of Object.entries(U).entries()){let J=Z?X(G,Y[1]):X(...Y,G);Q||=typeof J[0]==="number";let H=Array.isArray(J[0])||J.length===0?J:[J];for(let[W,$]of H)if(typeof W==="object")q[W.group]=g(q[W.group],$);else q[W]=$}return Q?Object.values(q):q};var y4=Object.entries;var n=(U,X)=>(U in X),K1=(U,X)=>(X in U);class k4{constructor(U){Object.assign(this,U)}}var CX=class{};class J2 extends CX{}var YG=(U,X)=>{let q={},Z={},Q;for(Q in U)if(Q in X)q[Q]=U[Q];else Z[Q]=U[Q];return[q,Z]};var _6=(U,X)=>YG(U,X)[1],S0=(U)=>Object.keys(U).length===0,J1=(U)=>[...Object.entries(U),...Object.getOwnPropertySymbols(U).map((X)=>[X,U[X]])],SX=(U,X)=>Object.defineProperties(U,Object.getOwnPropertyDescriptors(X)),EX=(U)=>{let X=Object.keys(U).sort(),q={};for(let Z=0;Z<X.length;Z++)q[X[Z]]=U[X[Z]];return q};var J0=D0(`unset${NX}`),jX=(U)=>Object.values(U).filter((X)=>{if(typeof X==="number")return!0;return typeof U[X]!=="number"});var v4={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},h4=globalThis.File??Blob,x4={ArrayBuffer,Blob,File:h4,FormData,Headers,Request,Response,URL},JG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},H1={...v4,...x4,...JG,String,Number,Boolean},H2=(U)=>{let X=Object.getPrototypeOf(U);while(X?.constructor&&(!n(X.constructor.name,H1)||!(U instanceof H1[X.constructor.name])))X=Object.getPrototypeOf(X);let q=X?.constructor?.name;if(q===void 0||q==="Object")return;return q},W2=(U)=>typeof U==="object"&&U!==null?H2(U)??"object":r(U);var h=Array.isArray,HG={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},WG={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},_G={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},bX={...HG,...WG,..._G},_2=(U)=>{let X=Object(U).name??null;return X&&n(X,H1)&&H1[X]===U?X:null};var u4=(U,X)=>{let q=U.prototype;while(q!==null){if(q===X.prototype)return!0;q=Object.getPrototypeOf(q)}return!1};var fX=(U)=>gX(U,new Map),gX=(U,X)=>{if(typeof U!=="object"||U===null)return U;if(X?.has(U))return X.get(U);let q=_2(U.constructor);if(q==="Date")return new Date(U.getTime());if(q&&q!=="Array")return U;let Z=Array.isArray(U)?U.slice():Object.create(Object.getPrototypeOf(U)),Q=Object.getOwnPropertyDescriptors(U);if(X){X.set(U,Z);for(let G in Q){let Y=Q[G];if("get"in Y||"set"in Y)continue;Y.value=gX(Y.value,X)}}return Object.defineProperties(Z,Q),Z};var $G=(U)=>{let X=J0;return()=>X===J0?X=U():X},d0=(U)=>typeof U==="function"&&U.length===0;var yX=class extends Function{constructor(...U){let X=U.slice(0,-1),q=U[U.length-1];try{super(...X,q)}catch(Z){return y(`Encountered an unexpected error while compiling your definition:
140
140
  Message: ${Z}
141
141
  Source: (${U.slice(0,-1)}) => {
142
142
  ${U[U.length-1]}
@@ -184,4 +184,4 @@ ${Y},
184
184
  fn("string", ":", "number")(s => s.length)`;class l9 extends H0{$;constructor(U){super((...X)=>new f2(U)(...X),{bind:U});this.$=U}in(U){return new f2(this.$,U===void 0?void 0:this.$.parse(U))}at(U,X){return new f2(this.$).at(U,X)}case(U,X){return new f2(this.$).case(U,X)}}class f2 extends H0{$;in;key;branches=[];constructor(U,X){super((q)=>this.caseEntries(Object.entries(q).map(([Z,Q])=>Z==="default"?[Z,Q]:[this.$.parse(Z),Q])));this.$=U,this.in=X}at(U,X){if(this.key)F(v7);if(this.branches.length)F(k7);return this.key=U,X?this.match(X):this}case(U,X){return this.caseEntry(this.$.parse(U),X)}caseEntry(U,X){let Z=(this.key?this.$.parse({[this.key]:U}):U).pipe(X);return this.branches.push(Z),this}match(U){return this(U)}strings(U){return this.caseEntries(Object.entries(U).map(([X,q])=>X==="default"?[X,q]:[this.$.node("unit",{unit:X}),q]))}caseEntries(U){for(let X=0;X<U.length;X++){let[q,Z]=U[X];if(q==="default"){if(X!==U.length-1)F("default may only be specified as the last key of a switch definition");return this.default(Z)}if(typeof Z!=="function")return F(`Value for case "${q}" must be a function (was ${r(Z)})`);this.caseEntry(q,Z)}return this}default(U){if(typeof U==="function")this.case(I.unknown,U);let X={branches:this.branches,ordered:!0};if(U==="never"||U==="assert")X.meta={onFail:mZ};let q=this.$.node("union",X);if(!this.in)return this.$.finalize(q);let Z=this.in.pipe(q);if(U==="never"||U==="assert")Z=Z.configureReferences({onFail:mZ},"self");return this.$.finalize(Z)}}var mZ=(U)=>U.throw(),k7="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",v7="At most one key matcher may be specified per expression";var v6=(U,X)=>{if(h(U)){if(U[1]==="=")return[X.$.parseOwnDefinitionFormat(U[0],X),"=",U[2]];if(U[1]==="?")return[X.$.parseOwnDefinitionFormat(U[0],X),"?"]}return h6(U,X)},pZ="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",lZ="Only required keys may specify default values, e.g. { value: 'number = 0' }";var dZ=(U,X)=>{let q,Z={},Q=J1(U);for(let[Y,J]of Q){let H=u7(Y);if(H.kind==="spread"){if(!S0(Z))return F(x7);let A=X.$.parseOwnDefinitionFormat(J,X);if(A.equals(I.object))continue;if(!A.hasKind("intersection")||!A.basis?.equals(I.object))return F(m7(A.expression));q=A.structure;continue}if(H.kind==="undeclared"){if(J!=="reject"&&J!=="delete"&&J!=="ignore")F(h7(J));Z.undeclared=J;continue}let W=v6(J,X),$=H;if(H.kind==="required"){if(!h(W))d9(Z,"required",{key:H.normalized,value:W},X);else d9(Z,"optional",W[1]==="="?{key:H.normalized,value:W[0],default:W[2]}:{key:H.normalized,value:W[0]},X);continue}if(h(W)){if(W[1]==="?")F(pZ);if(W[1]==="=")F(lZ)}if(H.kind==="optional"){d9(Z,"optional",{key:H.normalized,value:W},X);continue}let _=X.$.parseOwnDefinitionFormat($.normalized,X),L=K6(_,W,X.$);if(L.index)Z.index=g(Z.index,L.index);if(L.required)Z.required=g(Z.required,L.required)}let G=X.$.node("structure",Z);return X.$.parseSchema({domain:"object",structure:q?.merge(G)??G})},d9=(U,X,q,Z)=>{U[X]=g(U[X],Z.$.node(X,q))},h7=(U)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${E(U)})`,x7="Spread operator may only be used as the first key in an object",u7=(U)=>typeof U==="symbol"?{kind:"required",normalized:U}:U[U.length-1]==="?"?U[U.length-2]===W1?{kind:"required",normalized:`${U.slice(0,-2)}?`}:{kind:"optional",normalized:U.slice(0,-1)}:U[0]==="["&&U[U.length-1]==="]"?{kind:"index",normalized:U.slice(1,-1)}:U[0]===W1&&U[1]==="["&&U[U.length-1]==="]"?{kind:"required",normalized:U.slice(1)}:U==="..."?{kind:"spread"}:U==="+"?{kind:"undeclared"}:{kind:"required",normalized:U==="\\..."?"...":U==="\\+"?"+":U},m7=(U)=>`Spread operand must resolve to an object literal type (was ${U})`;var iZ=(U,X)=>a7(U)?nZ[U[0]](U,X):r7(U)?rZ[U[1]](U,X):null,p7=(U,X)=>X.$.parseOwnDefinitionFormat(U[1],X).keyof(),c9=(U,X)=>{if(U[2]===void 0)return F(v9(U[1],""));let q=X.$.parseOwnDefinitionFormat(U[0],X),Z=X.$.parseOwnDefinitionFormat(U[2],X);if(U[1]==="|")return X.$.node("union",{branches:[q,Z]});let Q=U[1]==="&"?$0(q,Z,X.$):D2(q,Z,X.$);if(Q instanceof T)return Q.throw();return Q},l7=(U,X)=>X.$.parseOwnDefinitionFormat(U[0],X).array(),d7=(U,X)=>{if(typeof U[2]!=="function")return F(sZ("=>",U[2]));return X.$.parseOwnDefinitionFormat(U[0],X).pipe(U[2])},sZ=(U,X)=>`${U===":"?"Narrow":"Morph"} expression requires a function following '${U}' (was ${typeof X})`,c7=(U,X)=>{if(typeof U[2]!=="function")return F(sZ(":",U[2]));return X.$.parseOwnDefinitionFormat(U[0],X).constrain("predicate",U[2])},i7=(U,X)=>X.$.parseOwnDefinitionFormat(U[0],X).configure(U[2],U[3]),oZ=(U)=>U,s7=oZ({"[]":l7,"?":()=>F(j6)}),o7=oZ({"|":c9,"&":c9,":":c7,"=>":d7,"|>":c9,"@":i7,"=":()=>F(b6)}),rZ={...s7,...o7},r7=(U)=>rZ[U[1]]!==void 0,n7=(U)=>U,nZ=n7({keyof:p7,instanceof:(U,X)=>{if(typeof U[1]!=="function")return F(cZ(W2(U[1])));let q=U.slice(1).map((Z)=>typeof Z==="function"?X.$.node("proto",{proto:Z}):F(cZ(W2(Z))));return q.length===1?q[0]:X.$.node("union",{branches:q})},"===":(U,X)=>X.$.units(U.slice(1))}),a7=(U)=>nZ[U[0]]!==void 0,cZ=(U)=>`Expected a constructor following 'instanceof' operator (was ${U})`;var eZ=(U,X)=>{let q=[{}],Z=0;while(Z<U.length){let Q=!1;if(U[Z]==="..."&&Z<U.length-1)Q=!0,Z++;let G=v6(U[Z],X),[Y,J,H]=!h(G)?[G]:G;if(Z++,Q){if(!Y.extends(O.intrinsic.Array))return F(UY(Y.expression));q=q.flatMap((W)=>Y.distribute(($)=>e7(A6(W),$)))}else q=q.map((W)=>{if(J==="?")return U8(W,Y);if(J==="=")return t7(W,Y,H);return i9(W,Y)})}return X.$.parseSchema(q.map((Q)=>S0(Q)?{proto:Array,exactLength:0}:{proto:Array,sequence:Q}))},i9=(U,X)=>{if(U.defaultables||U.optionals)return F(U.variadic?P9:XY);if(U.variadic)U.postfix=g(U.postfix,X);else U.prefix=g(U.prefix,X);return U},U8=(U,X)=>{if(U.variadic)return F(X8);return U.optionals=g(U.optionals,X),U},t7=(U,X,q)=>{if(U.variadic)return F(X8);if(U.optionals)return F(qY);return U.defaultables=g(U.defaultables,[[X,q]]),U},aZ=(U,X)=>{if(U.postfix)F(tZ);if(U.variadic){if(!U.variadic.equals(X))F(tZ)}else U.variadic=X.internal;return U},e7=(U,X)=>{let q=X.select({method:"find",kind:"sequence"});if(!q)return aZ(U,O.intrinsic.unknown);if(q.prefix)for(let Z of q.prefix)i9(U,Z);if(q.optionals)for(let Z of q.optionals)U8(U,Z);if(q.variadic)aZ(U,q.variadic);if(q.postfix)for(let Z of q.postfix)i9(U,Z);return U},UY=(U)=>`Spread element must be an array (was ${U})`,tZ="A tuple may have at most one variadic element",XY="A required element may not follow an optional element",X8="An optional element may not follow a variadic element";var qY="A defaultable element may not follow an optional element without a default";var ZY={},h6=(U,X)=>{if(typeof U==="string"){if(X.args&&Object.keys(X.args).some((Z)=>U.includes(Z)))return m9(U,X);let q=ZY[X.$.name]??={};return q[U]??=m9(U,X)}return G0(U,"object")?QY(U,X):F(s9(r(U)))},QY=(U,X)=>{let q=H2(U);switch(q){case void 0:if(M(U,"root"))return U;if("~standard"in U)return GY(U,X);return dZ(U,X);case"Array":return YY(U,X);case"RegExp":return X.$.node("intersection",{domain:"string",pattern:U},{prereduced:!0});case"Function":{let Z=d0(U)?U():U;if(M(Z,"root"))return Z;return F(s9("Function"))}default:return F(s9(q??E(U)))}},GY=(U,X)=>X.$.intrinsic.unknown.pipe((q,Z)=>{let Q=U["~standard"].validate(q);if(!Q.issues)return Q.value;for(let{message:G,path:Y}of Q.issues)if(Y)if(Y.length)Z.error({problem:uX(G),relativePath:Y.map((J)=>typeof J==="object"?J.key:J)});else Z.error({message:G});else Z.error({message:G})}),YY=(U,X)=>iZ(U,X)??eZ(U,X),s9=(U)=>`Type definitions must be strings or objects (was ${U})`;class o9 extends H0{constructor(U){let X=Object.assign({errors:W0,hkt:X0,$:U,raw:U.parse,module:U.constructor.module,scope:U.constructor.scope,declare:U.declare,define:U.define,match:U.match,generic:U.generic,schema:U.schema,keywords:U.ambient,unit:U.unit,enumerated:U.enumerated,instanceOf:U.instanceOf,valueOf:U.valueOf,or:U.or,and:U.and,merge:U.merge,pipe:U.pipe,fn:U.fn},U.ambientAttachments);super((...q)=>{if(q.length===1)return U.parse(q[0]);if(q.length===2&&typeof q[0]==="string"&&q[0][0]==="<"&&q[0][q[0].length-1]===">"){let Z=q[0].slice(1,-1),Q=U.parseGenericParams(Z,{});return new r0(Q,q[1],U,U,null)}return U.parse(q)},{attach:X})}}var l1=O;class x6 extends N6{get ambientAttachments(){if(!l1.typeAttachments)return;return this.cacheGetter("ambientAttachments",S(l1.typeAttachments,(U,X)=>[U,this.bindReference(X)]))}preparseOwnAliasEntry(U,X){let q=U.indexOf("<");if(q===-1){if(M(X,"module")||M(X,"generic"))return[U,X];let G=this.name==="ark"?U:U==="root"?this.name:`${this.name}.${U}`,Y=this.resolvedConfig.keywords?.[G];if(Y)X=[X,"@",Y];return[U,X]}if(U[U.length-1]!==">")F("'>' must be the last character of a generic declaration in a scope");let Z=U.slice(0,q),Q=U.slice(q+1,-1);return[Z,()=>{let G=this.parseGenericParams(Q,{alias:Z});return Fq(G,X,this)}]}parseGenericParams(U,X){return k6(new O2(U),[],this.createParseContext({...X,def:U,prefix:"generic"}))}normalizeRootScopeValue(U){if(d0(U)&&!M(U,"generic"))return U();return U}preparseOwnDefinitionFormat(U,X){return{...X,def:U,prefix:X.alias??"type"}}parseOwnDefinitionFormat(U,X){if(!(X.alias&&(X.alias in this.aliases))&&!X.args)X.args={this:X.id};let Z=h6(U,X);if(h(Z)){if(Z[1]==="=")return F(b6);if(Z[1]==="?")return F(j6)}return Z}unit=(U)=>this.units([U]);valueOf=(U)=>this.units(jX(U));enumerated=(...U)=>this.units(U);instanceOf=(U)=>this.node("proto",{proto:U},{prereduced:!0});or=(...U)=>this.schema(U.map((X)=>this.parse(X)));and=(...U)=>U.reduce((X,q)=>X.and(this.parse(q)),this.intrinsic.unknown);merge=(...U)=>U.reduce((X,q)=>X.merge(this.parse(q)),this.intrinsic.object);pipe=(...U)=>this.intrinsic.unknown.pipe(...U);fn=new p9(this);match=new l9(this);declare=()=>({type:this.type});define(U){return U}type=new o9(this);static scope=(U,X={})=>new x6(U,X);static module=(U,X={})=>this.scope(U,X).export()}var g2=Object.assign(x6.scope,{define:(U)=>U}),f=x6;class q8 extends X0{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var JY=T0(["base",I.object],["props",I.object])((U)=>U.base.merge(U.props),q8),Z8=f.module({Key:I.key,Merge:JY});class Q8 extends X0{}var HY=T0("element")((U)=>{let X=U.element.exclude(I.Array),q=X.array();return X.rawOr(q).pipe(l0).distribute((Z)=>Z.assertHasKind("morph").declareOut(q),v)},Q8),G8=f.module({root:I.Array,readonly:"root",index:I.nonNegativeIntegerString,liftFrom:HY},{name:"Array"});var r9=v(["string",_1.FileConstructor]),WY=r9.rawOr(r9.array()),Y8=v({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:WY}}),J8=f.module({root:["instanceof",FormData],value:r9,parsed:Y8,parse:v({in:FormData,morphs:(U)=>{let X={};for(let[q,Z]of U)if(q in X){let Q=X[q];if(typeof Q==="string"||Q instanceof _1.FileConstructor)X[q]=[Q,Z];else Q.push(Z)}else X[q]=Z;return X},declaredOut:Y8})},{name:"FormData"});var H8=f.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var _Y={Boolean:1,Number:1,String:1},W8=f.module({...S({...v4,...x4},(U,X)=>(U in _Y)?[]:[U,["instanceof",X]]),Array:G8,TypedArray:H8,FormData:J8});var $Y=v({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),LY=v({domain:"number",divisor:1}),u6=f.module({root:I.number,integer:LY,epoch:$Y,safe:v({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var l=(U,X,q)=>{let Z={domain:"string",pattern:{rule:U.source,flags:U.flags,meta:X}};if(q)Z.meta={format:q};return u1("intersection",Z)},_8=l($2,"a well-formed integer string"),M8=f.module({root:_8,parse:v({in:_8,morphs:(U,X)=>{let q=Number.parseInt(U);return Number.isSafeInteger(q)?q:X.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:I.integer})},{name:"string.integer"}),zY=l(/^[\dA-Fa-f]+$/,"hex characters only"),FY=f.module({root:l(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/,"base64-encoded"),url:l(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),$8=l(/^[A-Z].*$/,"capitalized"),AY=f.module({root:v({in:"string",morphs:(U)=>U.charAt(0).toUpperCase()+U.slice(1),declaredOut:$8}),preformatted:$8},{name:"string.capitalize"}),OY=(U)=>{let X=U.replace(/[ -]+/g,""),q=0,Z,Q,G=!1;for(let Y=X.length-1;Y>=0;Y--){if(Z=X.substring(Y,Y+1),Q=Number.parseInt(Z,10),G)Q*=2,q+=Q>=10?Q%10+1:Q;else q+=Q;G=!G}return!!(q%10===0?X:!1)},BY=/^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/,TY=v({domain:"string",pattern:{meta:"a credit card number",rule:BY.source},predicate:{meta:"a credit card number",predicate:OY}});var VY=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var RY=(U)=>!Number.isNaN(new Date(U).valueOf()),L8=v({domain:"string",predicate:{meta:"a parsable date",predicate:RY}}).assertHasKind("intersection"),z8=M8.root.internal.narrow((U,X)=>{let q=Number.parseInt(U),Z=u6.epoch(q);if(Z instanceof W0)return X.errors.merge(Z),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),DY=f.module({root:z8,parse:v({in:z8,morphs:(U)=>new Date(U),declaredOut:I.Date})},{name:"string.date.epoch"}),F8=l(VY,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),MY=f.module({root:F8,parse:v({in:F8,morphs:(U)=>new Date(U),declaredOut:I.Date})},{name:"string.date.iso"}),wY=f.module({root:L8,parse:v({declaredIn:L8,in:"string",morphs:(U,X)=>{let q=new Date(U);if(Number.isNaN(q.valueOf()))return X.error("a parsable date");return q},declaredOut:I.Date}),iso:MY,epoch:DY},{name:"string.date"}),PY=l(/^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/,"an email address","email"),A8="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",n0=`(${A8}[.]){3}${A8}`,IY=new RegExp(`^${n0}$`),c="(?:[0-9a-fA-F]{1,4})",KY=new RegExp(`^((?:${c}:){7}(?:${c}|:)|(?:${c}:){6}(?:${n0}|:${c}|:)|(?:${c}:){5}(?::${n0}|(:${c}){1,2}|:)|(?:${c}:){4}(?:(:${c}){0,1}:${n0}|(:${c}){1,3}|:)|(?:${c}:){3}(?:(:${c}){0,2}:${n0}|(:${c}){1,4}|:)|(?:${c}:){2}(?:(:${c}){0,3}:${n0}|(:${c}){1,5}|:)|(?:${c}:){1}(?:(:${c}){0,4}:${n0}|(:${c}){1,6}|:)|(?::((?::${c}){0,5}:${n0}|(?::${c}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),NY=f.module({root:["v4 | v6","@","an IP address"],v4:l(IY,"an IPv4 address","ipv4"),v6:l(KY,"an IPv6 address","ipv6")},{name:"string.ip"}),d1="a JSON string",w8=(U)=>{if(!(U instanceof SyntaxError))throw U;return`must be ${d1} (${U})`},CY=v({meta:d1,domain:"string",predicate:{meta:d1,predicate:(U,X)=>{try{return JSON.parse(U),!0}catch(q){return X.reject({code:"predicate",expected:d1,problem:w8(q)})}}}}),SY=(U,X)=>{if(U.length===0)return X.error({code:"predicate",expected:d1,actual:"empty"});try{return JSON.parse(U)}catch(q){return X.error({code:"predicate",expected:d1,problem:w8(q)})}},EY=f.module({root:CY,parse:v({meta:"safe JSON string parser",in:"string",morphs:SY,declaredOut:I.jsonObject})},{name:"string.json"}),O8=l(/^[a-z]*$/,"only lowercase letters"),jY=f.module({root:v({in:"string",morphs:(U)=>U.toLowerCase(),declaredOut:O8}),preformatted:O8},{name:"string.lower"}),P8=["NFC","NFD","NFKC","NFKD"],y2=S(P8,(U,X)=>[X,v({domain:"string",predicate:(q)=>q.normalize(X)===q,meta:`${X}-normalized unicode`})]),m6=S(P8,(U,X)=>[X,v({in:"string",morphs:(q)=>q.normalize(X),declaredOut:y2[X]})]),bY=f.module({root:m6.NFC,preformatted:y2.NFC},{name:"string.normalize.NFC"}),fY=f.module({root:m6.NFD,preformatted:y2.NFD},{name:"string.normalize.NFD"}),gY=f.module({root:m6.NFKC,preformatted:y2.NFKC},{name:"string.normalize.NFKC"}),yY=f.module({root:m6.NFKD,preformatted:y2.NFKD},{name:"string.normalize.NFKD"}),kY=f.module({root:"NFC",NFC:bY,NFD:fY,NFKC:gY,NFKD:yY},{name:"string.normalize"}),B8=l($6,"a well-formed numeric string"),vY=f.module({root:B8,parse:v({in:B8,morphs:(U)=>Number.parseFloat(U),declaredOut:I.number})},{name:"string.numeric"}),T8="a regex pattern",hY=v({domain:"string",predicate:{meta:T8,predicate:(U,X)=>{try{return new RegExp(U),!0}catch(q){return X.reject({code:"predicate",expected:T8,problem:String(q)})}}},meta:{format:"regex"}}),xY=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,uY=l(xY,"a semantic version (see https://semver.org/)"),V8=l(/^\S.*\S$|^\S?$/,"trimmed"),mY=f.module({root:v({in:"string",morphs:(U)=>U.trim(),declaredOut:V8}),preformatted:V8},{name:"string.trim"}),R8=l(/^[A-Z]*$/,"only uppercase letters"),pY=f.module({root:v({in:"string",morphs:(U)=>U.toUpperCase(),declaredOut:R8}),preformatted:R8},{name:"string.upper"}),lY=(U)=>URL.canParse(U),D8=v({domain:"string",predicate:{meta:"a URL string",predicate:lY},meta:{format:"uri"}}),dY=f.module({root:D8,parse:v({declaredIn:D8,in:"string",morphs:(U,X)=>{try{return new URL(U)}catch{return X.error("a URL string")}},declaredOut:v(URL)})},{name:"string.url"}),cY=f.module({root:["versioned | nil | max","@",{description:"a UUID",format:"uuid"}],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i,v1:l(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv1"),v2:l(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv2"),v3:l(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv3"),v4:l(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv4"),v5:l(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv5"),v6:l(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv6"),v7:l(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv7"),v8:l(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),I8=f.module({root:I.string,alpha:l(/^[A-Za-z]*$/,"only letters"),alphanumeric:l(/^[\dA-Za-z]*$/,"only letters and digits 0-9"),hex:zY,base64:FY,capitalize:AY,creditCard:TY,date:wY,digits:l(/^\d*$/,"only digits 0-9"),email:PY,integer:M8,ip:NY,json:EY,lower:jY,normalize:kY,numeric:vY,regex:hY,semver:uY,trim:mY,upper:pY,url:dY,uuid:cY},{name:"string"});var K8=f.module({bigint:I.bigint,boolean:I.boolean,false:I.false,never:I.never,null:I.null,number:I.number,object:I.object,string:I.string,symbol:I.symbol,true:I.true,unknown:I.unknown,undefined:I.undefined}),N8=f.module({root:I.unknown,any:I.unknown},{name:"unknown"}),iY=f.module({root:I.jsonObject,stringify:u1("morph",{in:I.jsonObject,morphs:(U)=>JSON.stringify(U),declaredOut:I.string})},{name:"object.json"}),C8=f.module({root:I.object,json:iY},{name:"object"});class S8 extends X0{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var sY=T0(["K",I.key],"V")((U)=>({domain:"object",index:{signature:U.K,value:U.V}}),S8);class E8 extends X0{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var oY=T0(["T",I.object],["K",I.key])((U)=>U.T.pick(U.K),E8);class j8 extends X0{description='omit a set of properties from an object like `Omit(User, "age")`'}var rY=T0(["T",I.object],["K",I.key])((U)=>U.T.omit(U.K),j8);class b8 extends X0{description="make all named properties of an object optional like `Partial(User)`"}var nY=T0(["T",I.object])((U)=>U.T.partial(),b8);class f8 extends X0{description="make all named properties of an object required like `Required(User)`"}var aY=T0(["T",I.object])((U)=>U.T.required(),f8);class g8 extends X0{description='exclude branches of a union like `Exclude("boolean", "true")`'}var tY=T0("T","U")((U)=>U.T.exclude(U.U),g8);class y8 extends X0{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var eY=T0("T","U")((U)=>U.T.extract(U.U),y8),k8=f.module({Exclude:tY,Extract:eY,Omit:rY,Partial:nY,Pick:oY,Record:sY,Required:aY});var x0=g2({...K8,...k8,...W8,...Z8,string:I8,number:u6,object:C8,unknown:N8},{prereducedAliases:!0,name:"ark"}),a=x0.export();Object.assign(l1.ambient,a);l1.typeAttachments={string:a.string.root,number:a.number.root,bigint:a.bigint,boolean:a.boolean,symbol:a.symbol,undefined:a.undefined,null:a.null,object:a.object.root,unknown:a.unknown.root,false:a.false,true:a.true,never:a.never,arrayIndex:a.Array.index,Key:a.Key,Record:a.Record,Array:a.Array.root,Date:a.Date};var n9=Object.assign(x0.type,l1.typeAttachments),UJ=x0.match,XJ=x0.fn,qJ=x0.generic,EN=x0.schema,ZJ=x0.define,QJ=x0.declare;var z1=g2({Operator:"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'",Condition:"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | StringOperatorCondition | HasKeyCondition | NullCondition | EmptyCondition | BasicCondition",RangeCondition:{field:"string > 0",operator:"'RANGE'",value:"unknown[] == 2"},ListCondition:{field:"string > 0",operator:"'IN' | 'NOT_IN'",value:"unknown[]"},ContainsCondition:{field:"string > 0",operator:"'CONTAINS' | 'NOT_CONTAINS'",value:"string | unknown[]"},StringOperatorCondition:{field:"string > 0",operator:"'STARTS_WITH' | 'ENDS_WITH'",value:"string"},HasKeyCondition:{field:"string > 0",operator:"'HAS_KEY'",value:"string"},NullCondition:{field:"string > 0",operator:"'IS_NULL' | 'IS_NONE'","value?":"boolean | null"},EmptyCondition:{field:"string > 0",operator:"'IS_EMPTY'","value?":"boolean | null"},NumericCondition:{field:"string > 0",operator:"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'",value:"number | string"},RegexCondition:{field:"string > 0",operator:"'MATCHES'",value:"string"},BasicCondition:{field:"string > 0",operator:"Operator",value:"unknown"},ConditionGroup:{operator:"'AND' | 'OR'",conditions:"(Condition | ConditionGroup)[] >= 1"},RuleCondition:"Condition | ConditionGroup",Action:{"type?":"string > 0","params?":"object","delay?":"number.integer >= 0 | string","probability?":"0 <= number <= 1 | string","if?":"RuleCondition | RuleCondition[]","then?":"Action | ActionGroup","else?":"Action | ActionGroup","break?":"boolean","continue?":"boolean"},ActionGroup:{"mode?":"'ALL' | 'EITHER' | 'SEQUENCE'",actions:"(Action | ActionGroup)[] >= 1"},RuleAction:"Action | ActionGroup",TriggerRule:{id:"string > 0","name?":"string","description?":"string","priority?":"number.integer","enabled?":"boolean","cooldown?":"number.integer >= 0","tags?":"string[]",on:"string > 0","if?":"RuleCondition | RuleCondition[]",do:"RuleAction | RuleAction[]","comment?":"string"}}).export(),oN=z1.Operator,rN=z1.Condition,nN=z1.ConditionGroup,aN=z1.RuleCondition,tN=z1.Action,eN=z1.ActionGroup,GJ=z1.TriggerRule;class a9{static validate(U){let X=GJ(U);if(X instanceof n9.errors){let Q=[];for(let G of X){let Y=G.path.join("."),J=G.message,H=void 0;if(Y.endsWith("on")&&(J.includes("string")||J.includes("must be")))if(typeof U==="object"&&U!==null&&"on"in U&&U.on===!0)J="The 'on' field is incorrect (boolean true found).",H=`In YAML, 'on' is a boolean keyword (true). Quote it: "on": "EventName"`;else H="Ensure 'on' is a string event name.";Q.push({path:Y,message:J,suggestion:H,severity:"error"})}return{valid:!1,issues:Q}}let q=X,Z=[];if(this.validateConditionsRecursive(q.if,Z,"if"),Z.length>0)return{valid:!1,issues:Z};return{valid:!0,rule:q}}static validateConditionsRecursive(U,X,q){if(!U)return;if(Array.isArray(U)){U.forEach((Z,Q)=>{this.validateConditionsRecursive(Z,X,`${q}.${Q}`)});return}if(typeof U==="object"&&U!==null&&"conditions"in U&&Array.isArray(U.conditions)){U.conditions.forEach((Z,Q)=>{this.validateConditionsRecursive(Z,X,`${q}.conditions.${Q}`)});return}if(typeof U==="object"&&U!==null&&"operator"in U&&"value"in U)this.validateConditionValue(U,X,q)}static validateConditionValue(U,X,q){let{operator:Z,value:Q}=U;if(typeof Z==="string"&&["IN","NOT_IN","RANGE","CONTAINS","NOT_CONTAINS"].includes(Z)){if(Z==="CONTAINS"){if(typeof Q!=="string"&&!Array.isArray(Q))X.push({path:`${q}.value`,message:`Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof Q}.`,suggestion:"Use a substring or a list of items.",severity:"error"});return}if(!Array.isArray(Q)){X.push({path:`${q}.value`,message:`Incorrect value type: Operator '${Z}' expects a List (Array), but received ${typeof Q}.`,suggestion:Z==="RANGE"?"Use format [min, max]":"Use format [item1, item2]",severity:"error"});return}if(Z==="RANGE"){if(Q.length!==2)X.push({path:`${q}.value`,message:"Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).",suggestion:"Use format [min, max], e.g. [1, 10]",severity:"error"});else if(typeof Q[0]!=="number"&&typeof Q[0]!=="string")X.push({path:`${q}.value`,message:"Incorrect range type: Range values must be numbers or expression strings.",severity:"error"})}}else if(Z==="MATCHES")if(typeof Q!=="string")X.push({path:`${q}.value`,message:`Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof Q}.`,severity:"error"});else try{new RegExp(Q)}catch(G){X.push({path:`${q}.value`,message:`Invalid Regex pattern: ${G.message}`,severity:"error"})}else if(typeof Z==="string"&&["GT","GTE","LT","LTE",">",">=","<","<="].includes(Z)){if(typeof Q!=="number"&&typeof Q!=="string")X.push({path:`${q}.value`,message:`Incorrect value type: Operator '${Z}' expects a number or expression string, but received ${typeof Q}.`,severity:"error"})}else if(typeof Z==="string"&&["STARTS_WITH","ENDS_WITH"].includes(Z)){if(typeof Q!=="string")X.push({path:`${q}.value`,message:`Incorrect value type: Operator '${Z}' expects a string, but received ${typeof Q}.`,severity:"error"})}else if(Z==="HAS_KEY"){if(typeof Q!=="string")X.push({path:`${q}.value`,message:`Incorrect value type: Operator 'HAS_KEY' expects a string (key name), but received ${typeof Q}.`,severity:"error"})}}}class p6{conditions=[];op="AND";constructor(U="AND"){this.op=U}where(U,X,q){return this.conditions.push({field:U,operator:X,value:q}),this}and(U){let X=new p6("AND");return this.conditions.push(U(X).build()),this}or(U){let X=new p6("OR");return this.conditions.push(U(X).build()),this}build(){if(this.conditions.length===0)throw Error("Condition group must have at least one condition");if(this.conditions.length===1&&this.op==="AND")return this.conditions[0];return{operator:this.op,conditions:this.conditions}}}class v8{actions=[];mode="ALL";setMode(U){return this.mode=U,this}add(U,X,q){return this.actions.push({type:U,params:X,...q}),this}build(){if(this.actions.length===0)throw Error("Action group must have at least one action");if(this.actions.length===1&&this.mode==="ALL")return this.actions[0];if(this.mode==="ALL")return this.actions;return{mode:this.mode,actions:this.actions}}}class YJ{rule={enabled:!0,priority:0};withId(U){return this.rule.id=U,this}withName(U){return this.rule.name=U,this}withDescription(U){return this.rule.description=U,this}withPriority(U){return this.rule.priority=U,this}withCooldown(U){return this.rule.cooldown=U,this}withTags(U){return this.rule.tags=U,this}on(U){return this.rule.on=U,this}if(U,X,q){if(!this.rule.if)this.rule.if={field:U,operator:X,value:q};else if(Array.isArray(this.rule.if))this.rule.if.push({field:U,operator:X,value:q});else this.rule.if=[this.rule.if,{field:U,operator:X,value:q}];return this}ifComplex(U){let X=new p6,q=U(X).build();return this.rule.if=q,this}do(U,X,q){let Z={type:U,params:X,...q};if(!this.rule.do)this.rule.do=Z;else if(Array.isArray(this.rule.do))this.rule.do.push(Z);else if(this.rule.do&&typeof this.rule.do==="object"&&"actions"in this.rule.do)this.rule.do.actions.push(Z);else this.rule.do=[this.rule.do,Z];return this}doComplex(U){let X=new v8,q=U(X).build();return this.rule.do=q,this}build(){if(!this.rule.id)throw Error("Rule ID is required");if(!this.rule.on)throw Error("Rule 'on' event is required");if(!this.rule.do)throw Error("Rule 'do' action is required");return this.rule}}var iQ=AX(WX(),1);class YO{static toYaml(U){let X=Array.isArray(U)?U:[U];return iQ.default.stringify(X)}static async saveToFile(U,X){let q=this.toYaml(U);if(typeof process<"u"&&process.versions&&process.versions.node){let Z=await import("fs/promises"),G=(await import("path")).dirname(X);await Z.mkdir(G,{recursive:!0}),await Z.writeFile(X,q,"utf8")}else throw Error("saveToFile is only supported in Node.js/Bun environments")}}import{existsSync as sQ,mkdirSync as JO,readFileSync as HO,writeFileSync as WO}from"fs";import{dirname as _O}from"path";class $O{filePath;cache=new Map;isLoaded=!1;constructor(U){this.filePath=U}ensureLoaded(){if(this.isLoaded)return;try{if(sQ(this.filePath)){let U=HO(this.filePath,"utf-8"),X=JSON.parse(U);this.cache=new Map(Object.entries(X))}}catch(U){console.error(`[FilePersistence] Failed to load state from ${this.filePath}:`,U),this.cache=new Map}this.isLoaded=!0}persist(){try{let U=_O(this.filePath);if(!sQ(U))JO(U,{recursive:!0});let X=Object.fromEntries(this.cache);WO(this.filePath,JSON.stringify(X,null,2),"utf-8")}catch(U){console.error(`[FilePersistence] Failed to save state to ${this.filePath}:`,U)}}async loadState(){return this.ensureLoaded(),new Map(this.cache)}async saveState(U,X){this.ensureLoaded(),this.cache.set(U,X),this.persist()}async deleteState(U){this.ensureLoaded(),this.cache.delete(U),this.persist()}async clearState(){this.cache.clear(),this.persist()}}import*as q2 from"path";import*as D1 from"fs";var oQ=AX(WX(),1);class LO{static async loadRulesFromDir(U){let X=[],q=async(Z)=>{let Q;try{Q=await D1.promises.readdir(Z,{withFileTypes:!0})}catch(G){console.error(`[TriggerLoader] Failed to readdir ${Z}:`,G);return}for(let G of Q){let Y=q2.resolve(Z,G.name);if(G.isDirectory())await q(Y);else if(Y.toLowerCase().endsWith(".yaml")||Y.toLowerCase().endsWith(".yml"))try{let J=await this.loadRule(Y);X.push(...J)}catch(J){console.error(`Failed to load rule from ${Y}:`,J)}}};if(D1.existsSync(U))await q(U);else console.warn(`[TriggerLoader] Directory not found: ${U}`);return X}static async loadRule(U){try{let X=await D1.promises.readFile(U,"utf-8"),q=oQ.parseAllDocuments(X);for(let Y of q)if(Y.errors&&Y.errors.length>0)throw Error(`YAML syntax error in ${U}: ${Y.errors.map((J)=>J.message).join(", ")}`);let Z=q.map((Y)=>Y.toJS()),Q=[],G=[];return Z.forEach((Y)=>{if(Array.isArray(Y))G.push(...Y);else G.push(Y)}),G.forEach((Y,J)=>{if(Y&&typeof Y==="object"&&Y!==null&&"actions"in Y&&!Y.do)Y.do=Y.actions;let H=a9.validate(Y);if(H.valid){let W=H.rule;if(!W.id&&typeof Y==="object"&&Y!==null){let $=q2.basename(U,q2.extname(U));W.id=G.length>1?`${$}-${J}`:$}Q.push(W)}else console.error(`
185
185
  [TriggerLoader] ⚠️ Validation Problem in ${U} (item #${J+1})`),H.issues.forEach((W)=>{if(console.error(` - [${W.path}] ${W.message}`),W.suggestion)console.error(` \uD83D\uDCA1 Suggestion: ${W.suggestion}`)})}),Q}catch(X){throw console.error(`Error parsing YAML file ${U}:`,X),X}}static watchRules(U,X){return this.loadRulesFromDir(U).then(X),console.log(`[TriggerLoader] Watching for changes in ${U}...`),D1.watch(U,{recursive:!0},async(Z,Q)=>{if(Q&&(String(Q).endsWith(".yaml")||String(Q).endsWith(".yml"))){console.log(`[TriggerLoader] Detected change in ${Q} (${Z}). Reloading rules...`);try{let G=await this.loadRulesFromDir(U);X(G),console.log(`[TriggerLoader] Reloaded ${G.length} rules.`)}catch(G){console.error("[TriggerLoader] Failed to reload rules:",G)}}})}}export{N0 as triggerEmitter,H6 as ruleEvents,VO as engineEvents,a9 as TriggerValidator,Y6 as TriggerUtils,GJ as TriggerRuleSchema,LO as TriggerLoader,G2 as TriggerEngine,f4 as TriggerEmitter,U0 as StateManager,YO as RuleExporter,VX as RuleEvent,g4 as RuleEngine,aN as RuleConditionSchema,YJ as RuleBuilder,b4 as InMemoryPersistence,$O as FilePersistence,e as ExpressionEngine,ZG as EventQueue,J6 as EngineEvent,G2 as Engine,GG as ContextAdapter,rN as ConditionSchema,nN as ConditionGroupSchema,p6 as ConditionBuilder,oN as ComparisonOperatorSchema,QG as BrowserPersistence,g4 as AdvancedRuleEngine,tN as ActionSchema,I1 as ActionRegistry,eN as ActionGroupSchema,v8 as ActionBuilder};
186
186
 
187
- //# debugId=19996B1AA99192A064756E2164756E21
187
+ //# debugId=AF0F8D138A9A4E5564756E2164756E21