@blue-labs/document-processor 1.32.1 → 1.33.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.
Files changed (42) hide show
  1. package/dist/BlueDocumentProcessor.d.ts.map +1 -1
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/context.d.ts +1 -1
  4. package/dist/context.d.ts.map +1 -1
  5. package/dist/index.js +4 -4
  6. package/dist/index.mjs +580 -491
  7. package/dist/processors/BaseChannelProcessor.d.ts.map +1 -1
  8. package/dist/processors/CompositeTimelineChannelProcessor.d.ts +3 -3
  9. package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +1 -1
  10. package/dist/processors/DocumentUpdateChannelProcessor.d.ts +3 -3
  11. package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +1 -1
  12. package/dist/processors/LifecycleEventChannelProcessor.d.ts +2 -2
  13. package/dist/processors/LifecycleEventChannelProcessor.d.ts.map +1 -1
  14. package/dist/processors/OperationProcessor.d.ts +3 -0
  15. package/dist/processors/OperationProcessor.d.ts.map +1 -1
  16. package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +1 -1
  17. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +6 -1
  18. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +1 -1
  19. package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts.map +1 -1
  20. package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +1 -1
  21. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts +1 -0
  22. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts.map +1 -1
  23. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts +1 -6
  24. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts.map +1 -1
  25. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionResolver.d.ts +8 -0
  26. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionResolver.d.ts.map +1 -0
  27. package/dist/processors/TriggeredEventChannelProcessor.d.ts +12 -0
  28. package/dist/processors/TriggeredEventChannelProcessor.d.ts.map +1 -0
  29. package/dist/processors/index.d.ts +1 -0
  30. package/dist/processors/index.d.ts.map +1 -1
  31. package/dist/routing/EventRouter.d.ts.map +1 -1
  32. package/dist/routing/buildContractEntries.d.ts +3 -0
  33. package/dist/routing/buildContractEntries.d.ts.map +1 -0
  34. package/dist/types.d.ts +3 -1
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/utils/EventTraceManager.d.ts +1 -0
  37. package/dist/utils/EventTraceManager.d.ts.map +1 -1
  38. package/dist/utils/expressionUtils.d.ts +4 -0
  39. package/dist/utils/expressionUtils.d.ts.map +1 -1
  40. package/package.json +5 -5
  41. package/dist/utils/fetchText.d.ts +0 -2
  42. package/dist/utils/fetchText.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"BlueDocumentProcessor.d.ts","sourceRoot":"","sources":["../src/BlueDocumentProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,YAAY,EAEZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAmBjB,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAI3C;;;;;GAKG;AACH,qBAAa,qBAAqB;IAc9B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAbvB,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IAEzD;;;;OAIG;gBAEgB,IAAI,EAAE,IAAI,EAC3B,UAAU,GAAE,iBAAiB,EAAsB;IAkBrD;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,EAAE,iBAAiB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAIzD;;;;;OAKG;IACG,UAAU,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAuBnE;;;;;;OAMG;IACG,aAAa,CACjB,QAAQ,EAAE,YAAY,EACtB,QAAQ,EAAE,gBAAgB,EAAE,GAC3B,OAAO,CAAC,gBAAgB,CAAC;IA8B5B;;OAEG;YACW,UAAU;CAsFzB"}
1
+ {"version":3,"file":"BlueDocumentProcessor.d.ts","sourceRoot":"","sources":["../src/BlueDocumentProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,YAAY,EAEZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAmBjB,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAI3C;;;;;GAKG;AACH,qBAAa,qBAAqB;IAc9B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAbvB,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IAEzD;;;;OAIG;gBAEgB,IAAI,EAAE,IAAI,EAC3B,UAAU,GAAE,iBAAiB,EAAsB;IAkBrD;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,EAAE,iBAAiB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAIzD;;;;;OAKG;IACG,UAAU,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAyBnE;;;;;;OAMG;IACG,aAAa,CACjB,QAAQ,EAAE,YAAY,EACtB,QAAQ,EAAE,gBAAgB,EAAE,GAC3B,OAAO,CAAC,gBAAgB,CAAC;IA8B5B;;OAEG;YACW,UAAU;CAsFzB"}
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE5C,eAAO,MAAM,iBAAiB,EAAE,iBAAiB,EAmBhD,CAAC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE5C,eAAO,MAAM,iBAAiB,EAAE,iBAAiB,EAoBhD,CAAC"}
package/dist/context.d.ts CHANGED
@@ -15,7 +15,7 @@ export declare class InternalContext implements ProcessingContext {
15
15
  resolvePath(path: string): string;
16
16
  getTaskInfo(): HandlerTask | undefined;
17
17
  getBlue(): Blue;
18
- loadExternalModule(url: string): Promise<string>;
18
+ loadExternalModule(): Promise<string>;
19
19
  loadBlueContent(blueId: string): Promise<string>;
20
20
  }
21
21
  //# sourceMappingURL=context.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EAClB,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE1D,qBAAa,eAAgB,YAAW,iBAAiB;IAIrD,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,OAAO,CAAC;IANlB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;gBAGxC,WAAW,EAAE,MAAM,YAAY,EAC/B,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,GAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,aAAA;IAGlE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB;IAMpC,QAAQ,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAUpC,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAa3B,KAAK,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAQ1C,WAAW,IAAI,MAAM;IAIrB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIjC,WAAW,IAAI,WAAW,GAAG,SAAS;IAItC,OAAO,IAAI,IAAI;IAMf,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAOhD,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAGjD"}
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EAClB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE1D,qBAAa,eAAgB,YAAW,iBAAiB;IAIrD,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,OAAO,CAAC;IANlB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;gBAGxC,WAAW,EAAE,MAAM,YAAY,EAC/B,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,GAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,aAAA;IAGlE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB;IAMpC,QAAQ,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAUpC,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAe3B,KAAK,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAQ1C,WAAW,IAAI,MAAM;IAIrB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIjC,WAAW,IAAI,WAAW,GAAG,SAAS;IAItC,OAAO,IAAI,IAAI;IAKf,kBAAkB,IAAI,OAAO,CAAC,MAAM,CAAC;IAIrC,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAQjD"}
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var ye=Object.defineProperty;var ge=(s,e,t)=>e in s?ye(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var l=(s,e,t)=>ge(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@blue-repository/core-dev"),p=require("@blue-labs/language"),T=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),Ee=(s,e)=>({on:(t,n)=>({end:()=>n(null)})});async function we(s){return new Promise((e,t)=>{Ee().on("error",t).end()})}const S=(...s)=>s.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<s.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class K{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=S(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:S(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n]};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return S(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(e){if(!/^https?:\/\//.test(e))throw new Error("Only http/https URLs are allowed");return we()}loadBlueContent(e){throw new Error("Not implemented")}}class j extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class x extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class q extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class $ extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function N(s){return T.deepFreeze(s)}function B(s){return s.clone()}function M(s,e,t="/",n=[]){const o=s.getContracts()??{};for(const[r,a]of Object.entries(o))if(e.isTypeOf(a,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(a,d.ProcessEmbeddedSchema).paths??[];for(const u of h)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(s.getProperties()??{}))M(a,e,S(t,r),n);return n}function J(s,e){return s===e||s.startsWith(e.endsWith("/")?e:e+"/")}function _(s,e){if(!e.length)return s;let t=B(s);for(const n of e)try{t=p.applyBlueNodePatch(t,n,!0)}catch(o){throw new j(n,o)}return N(t)}function E(s){return s!=null}function C(s){return s instanceof p.BlueNode}class ve{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,a=t[r];if(n(o,a)>=0)break;t[e]=a,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let a=(e<<1)+1;const c=a+1;if(c<this.length&&n(t[c],t[a])<0&&(a=c),n(t[a],r)>=0)break;t[e]=t[a],e=a}t[e]=r}}const Se=(s,e,t,n,o,r)=>[-s,e,t,n,o,r],be=(s,e)=>{for(let t=0;t<s.key.length;t++){const n=s.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Pe{constructor(){l(this,"queue");this.queue=new ve([],be)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Te{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}class Ce{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED==="true"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=[...e.trace??[],this.makeHop(t,n)];return{...e,trace:o}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}}const ke=64;class Ie{constructor(e,t,n,o,r){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new Ce}async route(e,t,n,o,r=0){var i;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const h=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,h,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const h=((i=n.originNodePath)==null?void 0:i.split("/").filter(Boolean))??[];return this.route(e,h,n,o,r)}}const a=S("/",t.join("/")),c=e.get(a);C(c)&&await this.traverseContracts({doc:e,node:c,nodePath:a,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:a,pathSegments:c,inlineDepth:i}=e;if(!this.shouldSkipForChannel(r,o))for(const[h,u]of Object.entries(n.getContracts()??{})){if(!u.getType())continue;const m=this.registry.get(u.getType());if(!m){console.warn(`No processor registered for contract: ${h}`);continue}const f={nodePath:o,contractName:h,contractNode:u,event:r},y=new K(()=>t,f,this.blue);if(m.supports(r,u,y,h))switch(m.role){case"adapter":await this.processAdapter({cp:m,event:r,contractNode:u,ctx:y,contractName:h,doc:t,afterTaskId:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,nodePath:o,event:r,depth:c.length,afterTaskId:a});break}}}async processAdapter(e){var v;const{cp:t,event:n,contractNode:o,ctx:r,contractName:a,doc:c,afterTaskId:i,inlineDepth:h}=e;if(h>=ke)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((v=r.getTaskInfo())==null?void 0:v.nodePath)??"",a);await t.handle(u,o,r,a);const m=await r.flush();if(m.find(b=>b.kind==="patch"))throw new Error(`Contract "${a}" (adapter) attempted to patch the document`);const y=m.filter(b=>b.kind==="event");for(const b of y)await this.route(c,[],b.event,i,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:a,afterTaskId:c}=e,i=t.getType();if(!i){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(i),u=t.get("/order"),m=p.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+c,y=Se(a,r.seq,h,m,n,f),v=this.traceManager.addHop(r,o,n);this.queue.push({key:y,nodePath:o,contractName:n,contractNode:t,event:v})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Ne=(s,e,t)=>{(t instanceof j||t instanceof x)&&console.error(`[Blue] Failed to apply patches for contract "${s}" on event ${JSON.stringify(e)}`,t)};function U(s,e){const t=B(s),n=o=>{if(!C(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!p.BlueNodeTypeSchema.isTypeOf(r.checkpoint,d.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:d.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of M(t,e)){const r=t.get(o);C(r)&&n(r)}return N(t)}function Be(s,e){const t=B(s);return C(t)&&(X(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),N(t)}function X(s,e){const t=s.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class Y{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",d.blueIds["Channel Event Checkpoint"]);l(this,"role","handler");this.cache=e}supports(e){var t,n;return e.source==="channel"&&((t=e.rootEvent)==null?void 0:t.payload)===e.payload&&((n=e.rootEvent)==null?void 0:n.source)==="external"}async getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof p.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var a;if(!e.channelName||!((a=e.rootEvent)!=null&&a.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const F=(s,e)=>s.get(e)!==void 0;class Oe{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const a=S(n,"contracts/checkpoint/lastEvents",o.channelName),c=`${a}/blueId`;F(e,a)?t.push({op:F(e,c)?"replace":"add",path:c,val:r}):t.push({op:"add",path:a,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class k{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class Z extends k{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"])}supports(t,n,o){const r=o.getBlue().nodeToSchemaOutput(n,d.CompositeTimelineChannelSchema);return!r.channels||!t.channelName?!1:r.channels.includes(t.channelName)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class G extends k{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o,r){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,d.DocumentUpdateChannelSchema),c=t.payload.get("/path");if(!c||t.channelName===r)return!1;const i=a.path;return T.isNonNullable(i)&&c===o.resolvePath(i)}handle(t,n,o,r){const a=t.payload;a&&o.emitEvent({payload:a,channelName:r,source:"channel"})}}class ee extends k{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",d.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema);return E(t.originNodePath)&&E(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:c,payload:i}=t;E(a.path)&&c===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}class te{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ne extends k{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",d.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,d.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var a;const r=(a=n.getProperties())==null?void 0:a.event;if(!r)return!0;try{const c=o.getBlue(),i=c.nodeToJson(t.payload),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during lifecycle event pattern matching:",c),!1}}}const L=(s,e)=>{const t=e.getBlue();return t.isTypeOf(s.payload,d.TimelineEntrySchema)||t.isTypeOf(s.payload,P.MyOSTimelineEntrySchema)};class oe extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!L(t,o))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,P.MyOSTimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),i=(u=a.timeline)==null?void 0:u.timelineId;return E(c.timelineId)&&E(i)&&i===c.timelineId}handle(t,n,o,r){L(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class re extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",P.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:a}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,a)&&this.isEventPatternMatch(r,a,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),a=r.nodeToSchemaOutput(t.payload,P.MyOSAgentEventSchema),c=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:a,myosAgentChannel:c}}isAgentMatch(t,n){var a;const o=t.agentId,r=(a=n.agent)==null?void 0:a.agentId;return E(o)&&E(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const a=t.event;if(!a)return!1;try{const c=o.getBlue(),i=c.nodeToJson(a),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during event pattern matching:",c),!1}}}class ae{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const a=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),c=this.parseEventPayload(e,n);return E(c==null?void 0:c.operation)&&c.operation===o&&e.source==="channel"&&e.channelName===a.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,d.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,d.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,d.OperationRequestSchema)}return null}}class se{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",d.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,d.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}const ce=!process.env.SKIP_ISOLATED_VM;let w=null;if(ce)try{w=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function z(s){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(s)||/\bexport\s+/.test(s)}class D{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!w||!ce?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(z(e))throw new Error("Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM.");try{if(n.isCodeBlock){const o=Object.keys(t);return await(await new Function(...o,`return async function codeBlock(${o.join(", ")}) { ${e} }`)(...o.map(c=>t[c])))(...o.map(c=>t[c]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new $(e,o):new q(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!w)throw new Error("isolated-vm not available");const r=new w.Isolate({memoryLimit:32}),a=await r.createContext(),c=a.global;try{await this.setupIsolateEnvironment(c,t);const i=new Map,h=this.createModuleResolver(r,a,i,n);let u;return z(e)?u=await this.evaluateESModule(r,a,e,o,h):u=await this.evaluateSimpleScript(r,a,e,t,o),this.deepClone(u)}catch(i){throw o.isCodeBlock?new $(e,i):new q(e,i)}finally{a.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!w)throw new Error("isolated-vm not available");const n=new w.Callback((...r)=>console.log(...r)),o=new w.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,a]of Object.entries(t))typeof a=="function"?await e.set(r,new w.Callback(a)):await e.set(r,new w.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const a=r.slice(5),c=o.loadBlueContent;if(typeof c!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const i=await c(a),h=await e.compileModule(i);return n.set(r,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(r)){let a;if(typeof o.loadExternalModule=="function")a=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const c=await e.compileModule(a);return n.set(r,c),await c.instantiate(t,this.createModuleResolver(e,t,n,o)),c}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const a=Object.keys(o).join(", "),c=Object.keys(o).map(u=>u),i=`(async (${a}) => { ${r.isCodeBlock?n:`return (${n});`} })(${c.join(", ")})`;return await(await e.compileScript(i)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let a=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
2
- `),m=n.replace(h,"").trim();a=`
1
+ "use strict";var ve=Object.defineProperty;var we=(a,e,t)=>e in a?ve(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var l=(a,e,t)=>we(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@blue-repository/core-dev"),m=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),C=require("@blue-repository/myos-dev"),S=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class G{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=S(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:S(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return S(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class V extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class _ extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class K extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class Y extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(a){return v.deepFreeze(a)}function M(a){return a.clone()}function D(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(s,d.ProcessEmbeddedSchema).paths??[];for(const u of h)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))D(s,e,S(t,r),n);return n}function U(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function z(a,e){if(!e.length)return a;let t=M(a);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new V(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class Te{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Pe=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],be=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Se{constructor(){l(this,"queue");this.queue=new Te([],be)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Ce{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}const O=class O{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=O.MAX_TRACE_LENGTH?o.slice(o.length-(O.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}};l(O,"MAX_TRACE_LENGTH",128);let j=O;function Ne(a){return Object.entries(a.getContracts()??{})}const Ie=64;class ke{constructor(e,t,n,o,r){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new j}async route(e,t,n,o,r=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const h=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,h,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const h=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,h,n,o,r)}}const s=S("/",t.join("/")),i=e.get(s);N(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[h,u]of Ne(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${h}`);continue}const f={nodePath:o,contractName:h,contractNode:u,event:r},g=new G(()=>t,f,this.blue);if(p.supports(r,u,g,h))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:h,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var P;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:h}=e;if(h>=Ie)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((P=r.getTaskInfo())==null?void 0:P.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(T=>T.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(T=>T.kind==="event");for(const T of g)await this.route(i,[],T.event,c,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(c),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+i,g=r.seq;if(g===void 0)throw new Error("Event sequence missing");const P=Pe(s,g,h,p,n,f);{const y=`${o}#${n}`,A=r.trace??[];if(r.source!=="external"&&A.includes(y))throw new Error(`Loop detected: repeated hop ${y} within the same event chain`)}const T=this.traceManager.addHop(r,o,n);this.queue.push({key:P,nodePath:o,contractName:n,contractNode:t,event:T})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Be=(a,e,t)=>{(t instanceof V||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function H(a,e){const t=M(a),n=o=>{if(!N(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!m.BlueNodeTypeSchema.isTypeOf(r.checkpoint,d.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:d.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const r=t.get(o);N(r)&&n(r)}return B(t)}function Oe(a,e){const t=M(a);return N(t)&&(Z(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),B(t)}function Z(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ee{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",d.blueIds["Channel Event Checkpoint"]);l(this,"role","handler");this.cache=e}supports(e){var t,n;return e.source==="channel"&&((t=e.rootEvent)==null?void 0:t.payload)===e.payload&&((n=e.rootEvent)==null?void 0:n.source)==="external"}async getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof m.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var s;if(!e.channelName||!((s=e.rootEvent)!=null&&s.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const F=(a,e)=>a.get(e)!==void 0;class Me{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const s=S(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;F(e,s)?t.push({op:F(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class te{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,d.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class I{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class ne extends I{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.DocumentUpdateChannelSchema),s=t.payload.get("/path");if(!s)return!1;const i=r.path;return v.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class oe extends I{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",d.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema);return w(t.originNodePath)&&w(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const s=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;w(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class re{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class se extends I{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",d.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||t.emissionType!=="lifecycle"||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel",emissionType:t.emissionType})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,d.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var s;const r=(s=n.getProperties())==null?void 0:s.event;if(!r)return!0;try{const i=o.getBlue(),c=i.resolve(t.payload);return i.isTypeOfNode(c,r)}catch(i){return console.warn("Error during lifecycle event pattern matching:",i),!1}}}const R=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,d.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ae extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",C.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!R(t,o))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,C.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,C.MyOSTimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){R(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ie extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",C.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:s}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,s)&&this.isEventPatternMatch(r,s,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),s=r.nodeToSchemaOutput(t.payload,C.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,C.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var s;const o=t.agentId,r=(s=n.agent)==null?void 0:s.agentId;return w(o)&&w(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const s=t.event;if(!s)return!1;try{const i=o.getBlue(),c=i.nodeToJson(s),h=i.nodeToJson(r);return v.deepContains(c,h)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class ce{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),h=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&h&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,d.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,d.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,d.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return w(e==null?void 0:e.operation)&&(e==null?void 0:e.operation)===t}isOperationChannelMatch(e,t){const n=t.channel;return v.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(v.isNullable(o))return!0;const r=n.getBlue(),s=e==null?void 0:e.request;if(v.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class le{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",d.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,d.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}let E=null;try{E=require("isolated-vm")}catch{E=null}function qe(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class ${static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(!E)throw new Error("isolated-vm is required for expression evaluation");return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!E)throw new Error("isolated-vm not available");const r=new E.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,h=this.createModuleResolver(r,s,c,n);let u;return qe(e)?u=await this.evaluateESModule(r,s,e,o,h):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new Y(e,c):new K(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!E)throw new Error("isolated-vm not available");const n=new E.Callback((...r)=>console.log(...r)),o=new E.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,s]of Object.entries(t))typeof s=="function"?await e.set(r,new E.Callback(s)):await e.set(r,new E.ExternalCopy(s).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const s=r.slice(5),i=o.loadBlueContent;if(typeof i!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const c=await i(s),h=await e.compileModule(c);return n.set(r,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(r)){let s;if(typeof o.loadExternalModule=="function")s=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const i=await e.compileModule(s);return n.set(r,i),await i.instantiate(t,this.createModuleResolver(e,t,n,o)),i}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const s=Object.keys(o).join(", "),i=Object.keys(o).map(u=>u),c=`(async (${s}) => { ${r.isCodeBlock?n:`return (${n});`} })(${i.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let s=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
2
+ `),p=n.replace(h,"").trim();s=`
3
3
  ${u}
4
4
  const run = function() {
5
- ${m}
5
+ ${p}
6
6
  };
7
7
  export default run();
8
- `}const c=await e.compileModule(a);return await c.instantiate(t,r),await c.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await c.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class A{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),a=p.isBigNumber(r)?r.toNumber():r;return{document:c=>{const i=e.get(c);return p.isBigNumber(i)?i.toNumber():C(i)?o.nodeToJson(i,"original"):i},event:a,steps:n}}}function R(s,e){const{op:t,path:n,val:o,from:r}=s;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const a={type:"Document Update",op:t,path:n};return o!==void 0&&(a.val=o),r!==void 0&&(a.from=r),e.jsonValueToNode(a)}function Me(s){return s.jsonValueToNode({type:"Document Processing Initiated"})}const qe=/^\$\{(.*)\}$/,O=s=>typeof s!="string"?!1:qe.test(s),H=s=>{if(!O(s))throw new Error(`Invalid expression: ${s}`);return s.slice(2,-1)};class $e{constructor(){l(this,"stepType","Update Document")}supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const a=n.getBlue();if(!p.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const c=await this.evaluateChangeset(e.get("/changeset"),n,t,r),i=p.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:c}),h=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const u of h.changeset??[]){if(!u.path)continue;const m=u.val;if((u.op==="replace"||u.op==="add")&&T.isNonNullable(m)){const f=await this.evaluateChangeValue(m,n,t,r);n.addPatch({op:u.op,path:u.path,val:f}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:a.nodeToJson(f,"original")},a)})}u.op==="remove"&&(n.addPatch({op:u.op,path:u.path}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:null},a)}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(O(e)){const a=H(e),c=await D.evaluate({code:a,ctx:t,bindings:A.createStandardBindings(t,n,o)});return r.jsonValueToNode(c??null)}if(C(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),a=t.getBlue();if(O(r)){const c=H(r),i=await D.evaluate({code:c,ctx:t,bindings:A.createStandardBindings(t,n,o)});return a.jsonValueToNode(i??null)}return e}}class De{constructor(){l(this,"stepType","Trigger Event")}supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!p.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,d.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event})}}class Ae{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!p.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const a=n.getBlue(),c=a.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!c.code)throw new Error("JavaScript code is required");const i=await D.evaluate({code:c.code,ctx:n,bindings:A.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(i&&typeof i=="object"&&"events"in i){const h=i;if(Array.isArray(h.events))for(const u of h.events)n.emitEvent({payload:a.jsonValueToNode(u)})}return i}}const je=[new $e,new De,new Ae];class V{constructor(e=je){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",d.blueIds["Sequential Workflow"]);l(this,"role","handler");l(this,"executors",[]);this.executors=e}registerExecutor(e){this.executors.push(e)}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowSchema).channel;return e.source==="channel"&&e.channelName===a}async handle(e,t,n,o){var c;const r={},a=(c=t.getProperties())==null?void 0:c.steps.getItems();for(const[i,h]of(a??[]).entries()){const u=this.executors.find(f=>f.supports(h));if(!u)throw new Error(`Unsupported workflow step type "${h.getType()}"`);const m=await u.execute(h,e,n,o,r);if(m!==void 0){const f=h.getName(),y=typeof f=="string"?f:`Step${i+1}`;r[y]=m}await n.flush()}}}class ie{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",d.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new V}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,c=e.channelName;return e.source==="channel"&&T.isNonNullable(c)&&T.isNonNullable(a)&&c===a}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const Q=s=>p.BlueNodeTypeSchema.isTypeOf(s.payload,d.TimelineEntrySchema);class le extends k{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",d.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(u=a.timeline)==null?void 0:u.timelineId;return E(c.timelineId)&&E(i)&&i===c.timelineId}handle(t,n,o,r){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const xe=[new se,new ee,new G,new le,new oe,new re,new Z,new ne,new ae,new V,new ie,new te];class Ve{constructor(e,t=xe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Oe);this.blue=e,this.registry=new Te(t),this.queue=new Pe,this.router=new Ie(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new Y(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=U(N(e),this.blue);const n={payload:Me(this.blue)},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=Be(t,this.blue),{state:B(t),emitted:o}}async processEvents(e,t){let n=U(N(e),this.blue);const o=[];if(!X(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const a={payload:r,source:"external"};await this.router.route(n,[],a,0);const c=await this.drainQueue(n);n=c.state,o.push(...c.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=_(n,i))}finally{this.checkpointCache.clear()}return{state:B(n),emitted:o}}async drainQueue(e){var a;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const c=this.queue.pop(),{nodePath:i,contractName:h,contractNode:u,event:m}=c,f=t.get(i);if(!C(f)||!((a=f.getContracts())!=null&&a[h])||!u.getType())continue;const y=this.registry.get(u.getType());if(!y){console.warn(`No processor registered for contract: ${h}`);continue}const v=new K(()=>t,c,this.blue,async b=>{for(const g of b)if(g.kind==="patch"){const he=M(t,this.blue);for(const I of he){const de=g.patch.op==="move"||g.patch.op==="copy"?[g.patch.from,g.patch.path]:[g.patch.path],W=v.getNodePath(),pe=de.some(fe=>J(fe,I.absPath)),me=J(W,I.absPath);if(pe&&!me)throw new x(g.patch,I.absPath,W)}try{t=_(t,[g.patch])}catch(I){throw Ne(h,m,I),I}}else g.kind==="event"&&(n.push(g.event.payload),await this.router.route(t,[],g.event,c.key[5]))});await y.handle(m,u,v,h),await v.flush()}return{state:t,emitted:n}}}class ue{process(e,t){const n=t.getValue();if(O(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(O(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const We=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ue},Symbol.toStringTag,{value:"Module"}));function Je(){return new p.MergingProcessors.SequentialMergingProcessor([new p.MergingProcessors.ValuePropagator,new ue,new p.MergingProcessors.TypeAssigner,new p.MergingProcessors.ListProcessor,new p.MergingProcessors.DictionaryProcessor,new p.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Ve;exports.ChannelEventCheckpointProcessor=Y;exports.CodeBlockEvaluationError=$;exports.CompositeTimelineChannelProcessor=Z;exports.DocumentUpdateChannelProcessor=G;exports.EmbeddedDocumentModificationError=x;exports.EmbeddedNodeChannelProcessor=ee;exports.ExpressionEvaluationError=q;exports.InitializedMarkerProcessor=te;exports.LifecycleEventChannelProcessor=ne;exports.MergingProcessors=We;exports.MyOSAgentChannelProcessor=re;exports.MyOSTimelineChannelProcessor=oe;exports.OperationProcessor=ae;exports.PatchApplicationError=j;exports.ProcessEmbeddedProcessor=se;exports.SequentialWorkflowOperationProcessor=ie;exports.SequentialWorkflowProcessor=V;exports.TimelineChannelProcessor=le;exports.collectEmbeddedPathSpecs=M;exports.createDefaultMergingProcessor=Je;
8
+ `}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class W{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=m.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return m.isBigNumber(c)?c.toNumber():N(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const $e=/^\$\{([\s\S]*)\}$/,De=/\$\{([\s\S]*?)\}/,b=a=>typeof a!="string"?!1:$e.test(a),x=a=>typeof a!="string"?!1:De.test(a),ue=a=>{if(!b(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return W.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(b(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(x(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await $.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function X(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function Ae(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class je{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),h=n.getBlue().nodeToSchemaOutput(c,d.UpdateDocumentSchema);for(const u of h.changeset??[]){if(!u.path)continue;const p=await this.evaluateChangePath(u.path,n,t,r),f=u.val;if((u.op==="replace"||u.op==="add")&&v.isNonNullable(f)){const g=await this.evaluateChangeValue(f,n,t,r);n.addPatch({op:u.op,path:p,val:g}),n.emitEvent({payload:X({op:u.op,path:n.resolvePath(p),val:s.nodeToJson(g,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:p}),n.emitEvent({payload:X({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(b(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:W.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}if(N(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),s=t.getBlue();if(b(r)||typeof r=="string"&&x(r)){const i=q.createBindings(t,n,o),c=await q.evaluate(String(r),t,i,{coerceToString:!b(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=q.createBindings(t,n,o);if(b(e)||x(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class xe{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,d.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class Ve{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await $.evaluate({code:i.code,ctx:n,bindings:W.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const h=c;if(Array.isArray(h.events))for(const u of h.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const _e=[new je,new xe,new Ve];class J{constructor(e=_e){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",d.blueIds["Sequential Workflow"]);l(this,"role","handler");l(this,"executors",[]);this.executors=e}registerExecutor(e){this.executors.push(e)}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){var i;const r={},s=(i=t.getProperties())==null?void 0:i.steps.getItems();for(const[c,h]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(h));if(!u)throw new Error(`Unsupported workflow step type "${h.getType()}"`);const p=await u.execute(h,e,n,o,r);if(p!==void 0){const f=h.getName(),g=typeof f=="string"?f:`Step${c+1}`;r[g]=p}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return v.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){var r;const o=(r=t.getProperties())==null?void 0:r.event;if(!o)return!0;try{const s=n.getBlue(),i=s.resolve(e.payload);return s.isTypeOfNode(i,o)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class he{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",d.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new J}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&v.isNonNullable(i)&&v.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const Q=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,d.TimelineEntrySchema);class de extends I{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",d.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class pe extends I{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",d.blueIds["Triggered Event Channel"])}supports(t){return this.baseSupports(t)?t.emissionType==="triggered":!1}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const We=[new le,new oe,new ne,new de,new ae,new ie,new te,new se,new pe,new ce,new J,new he,new re];class Je{constructor(e,t=We){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Me);this.blue=e,this.registry=new Ce(t),this.queue=new Se,this.router=new ke(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ee(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=H(B(e),this.blue);const n={payload:Ae(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=Oe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=H(B(e),this.blue);const o=[];if(!Z(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=z(n,c))}finally{this.checkpointCache.clear()}return{state:M(n),emitted:o}}async drainQueue(e){var s;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const i=this.queue.pop(),{nodePath:c,contractName:h,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[h])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${h}`);continue}const P=new G(()=>t,i,this.blue,async T=>{for(const y of T)if(y.kind==="patch"){const A=D(t,this.blue);for(const k of A){const fe=y.patch.op==="move"||y.patch.op==="copy"?[y.patch.from,y.patch.path]:[y.patch.path],L=P.getNodePath(),ge=fe.some(Ee=>U(Ee,k.absPath)),ye=U(L,k.absPath);if(ge&&!ye)throw new _(y.patch,k.absPath,L)}try{t=z(t,[y.patch])}catch(k){throw Be(h,p,k),k}}else y.kind==="event"&&(n.push(y.event.payload),await this.router.route(t,[],y.event,i.key[5]))});await g.handle(p,u,P,h),await P.flush()}return{state:t,emitted:n}}}class me{process(e,t){const n=t.getValue();if(b(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(b(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Le=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:me},Symbol.toStringTag,{value:"Module"}));function Ue(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new me,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Je;exports.ChannelEventCheckpointProcessor=ee;exports.CodeBlockEvaluationError=Y;exports.CompositeTimelineChannelProcessor=te;exports.DocumentUpdateChannelProcessor=ne;exports.EmbeddedDocumentModificationError=_;exports.EmbeddedNodeChannelProcessor=oe;exports.ExpressionEvaluationError=K;exports.InitializedMarkerProcessor=re;exports.LifecycleEventChannelProcessor=se;exports.MergingProcessors=Le;exports.MyOSAgentChannelProcessor=ie;exports.MyOSTimelineChannelProcessor=ae;exports.OperationProcessor=ce;exports.PatchApplicationError=V;exports.ProcessEmbeddedProcessor=le;exports.SequentialWorkflowOperationProcessor=he;exports.SequentialWorkflowProcessor=J;exports.TimelineChannelProcessor=de;exports.TriggeredEventChannelProcessor=pe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ue;