@blue-labs/document-processor 1.21.1 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -5
- package/dist/index.mjs +441 -588
- package/dist/processors/ChannelEventCheckpointProcessor.d.ts +1 -1
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +1 -1
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts +1 -1
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +1 -1
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts +1 -1
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts.map +1 -1
- package/dist/processors/MyOSAgentChannelProcessor.d.ts +1 -1
- package/dist/processors/MyOSAgentChannelProcessor.d.ts.map +1 -1
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts.map +1 -1
- package/dist/processors/OperationProcessor.d.ts +1 -1
- package/dist/processors/ProcessEmbeddedProcessor.d.ts +1 -1
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +1 -1
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +1 -1
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +1 -1
- package/dist/processors/TimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/TimelineChannelProcessor.d.ts.map +1 -1
- package/dist/utils/checkpoint.d.ts.map +1 -1
- package/package.json +5 -6
- package/dist/repo/core/blue-ids/index.d.ts +0 -21
- package/dist/repo/core/blue-ids/index.d.ts.map +0 -1
- package/dist/repo/core/index.d.ts +0 -199
- package/dist/repo/core/index.d.ts.map +0 -1
- package/dist/repo/core/schema/Channel.d.ts +0 -13
- package/dist/repo/core/schema/Channel.d.ts.map +0 -1
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts +0 -17
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts +0 -17
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts +0 -17
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/JavaScriptCode.d.ts +0 -10
- package/dist/repo/core/schema/JavaScriptCode.d.ts.map +0 -1
- package/dist/repo/core/schema/JsonPatchEntry.d.ts +0 -22
- package/dist/repo/core/schema/JsonPatchEntry.d.ts.map +0 -1
- package/dist/repo/core/schema/Operation.d.ts +0 -16
- package/dist/repo/core/schema/Operation.d.ts.map +0 -1
- package/dist/repo/core/schema/OperationRequest.d.ts +0 -29
- package/dist/repo/core/schema/OperationRequest.d.ts.map +0 -1
- package/dist/repo/core/schema/ProcessEmbedded.d.ts +0 -10
- package/dist/repo/core/schema/ProcessEmbedded.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflow.d.ts +0 -13
- package/dist/repo/core/schema/SequentialWorkflow.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts +0 -15
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts +0 -13
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts.map +0 -1
- package/dist/repo/core/schema/TimelineChannel.d.ts +0 -17
- package/dist/repo/core/schema/TimelineChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/TimelineEntry.d.ts +0 -25
- package/dist/repo/core/schema/TimelineEntry.d.ts.map +0 -1
- package/dist/repo/core/schema/TriggerEvent.d.ts +0 -10
- package/dist/repo/core/schema/TriggerEvent.d.ts.map +0 -1
- package/dist/repo/core/schema/UpdateDocument.d.ts +0 -40
- package/dist/repo/core/schema/UpdateDocument.d.ts.map +0 -1
- package/dist/repo/core/schema/index.d.ts +0 -15
- package/dist/repo/core/schema/index.d.ts.map +0 -1
- package/dist/repo/myos/blue-ids/index.d.ts +0 -8
- package/dist/repo/myos/blue-ids/index.d.ts.map +0 -1
- package/dist/repo/myos/index.d.ts +0 -101
- package/dist/repo/myos/index.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgent.d.ts +0 -10
- package/dist/repo/myos/schema/MyOSAgent.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts +0 -30
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts +0 -19
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts +0 -24
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts +0 -32
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts.map +0 -1
- package/dist/repo/myos/schema/index.d.ts +0 -6
- package/dist/repo/myos/schema/index.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var ge=Object.defineProperty;var Ee=(i,e,t)=>e in i?ge(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var l=(i,e,t)=>Ee(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("zod"),d=require("@blue-labs/language"),k=require("@blue-labs/shared-utils"),we=(i,e)=>({on:(t,n)=>({end:()=>n(null)})});async function Ce(i){return new Promise((e,t)=>{we().on("error",t).end()})}const P=(...i)=>i.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<i.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class L{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=P(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:P(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 P(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 Ce()}loadBlueContent(e){throw new Error("Not implemented")}}class H 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 V extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class W extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}const m={Channel:"2RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc","Timeline Channel":"RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Composite Timeline Channel":"qxkh3uMkKoutP5DxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow":"h3uDxZ7dr6Eo27B7fuxMkKoutP5qxkQCS1VAptiCPc2R","Process Embedded":"DxZ7dr6EoMkKoutP5qxkh3u27B7fuxQCS1VAptiCPc2R","Embedded Node Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Document Update Channel":"MkKoutP5qxkh3uDQCS1VAptiCPc2xZ7dr6Eo27B7fux","Channel Event Checkpoint":"o27B7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Update Document":"7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Trigger Event":"kQCS1VAp7fuxMkKoutPh3uDxZ7dr6E5qxtiCPc2R","Json Patch Entry":"EnUQeMiMa2wHFW3JbeSPvdgfpL6qZYCR29m3SfeHsKSY","JavaScript Code":"MkKoutPDxZ7dr6Eo5qxkh3u27B7fuxQCS1VAptiCPc2R","Timeline Entry":"uDxZ7dr6Eo27B7fMkKoutP5qxkh3uxQCS1VAptiCPc2R",Operation:"OpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow Operation":"SeqOpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC","Operation Request":"OpReqKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC"},I=d.withTypeBlueId(m.Channel)(u.z.object({name:u.z.string().optional(),description:u.z.string().optional()})),Se=d.withTypeBlueId(m["Composite Timeline Channel"])(I.extend({channels:u.z.array(u.z.string()).optional()})),Pe=d.withTypeBlueId(m["Document Update Channel"])(I.extend({path:u.z.string().optional()})),R=d.withTypeBlueId(m["Embedded Node Channel"])(I.extend({path:u.z.string().optional()})),x=d.withTypeBlueId(m["JavaScript Code"])(u.z.object({code:u.z.string().optional()})),Te=d.withTypeBlueId(m.Operation)(u.z.object({request:d.blueNodeField().optional(),description:u.z.string().optional(),channel:u.z.string().optional()})),ve=d.withTypeBlueId(m["Operation Request"])(u.z.object({operation:u.z.string().optional(),request:d.blueNodeField(),document:u.z.object({blueId:u.z.string().optional()}).optional(),allowNewerVersion:u.z.boolean().optional()})),A=d.withTypeBlueId(m["Process Embedded"])(u.z.object({paths:u.z.array(u.z.string()).optional()})),z=d.withTypeBlueId(m["Sequential Workflow"])(u.z.object({steps:u.z.array(d.blueNodeField()).optional(),channel:u.z.string().optional()})),be=d.withTypeBlueId(m["Sequential Workflow Operation"])(z.omit({channel:!0}).extend({operation:u.z.string().optional()})),Y=d.withTypeBlueId(m["Timeline Channel"])(I.extend({timelineId:u.z.string().optional()})),O=d.withTypeBlueId(m["Timeline Entry"])(u.z.object({timelineId:u.z.string().optional(),timelinePrev:u.z.string().optional(),thread:u.z.string().optional(),threadPrev:u.z.string().optional(),message:d.blueNodeField().optional(),signature:u.z.string().optional()})),M=d.withTypeBlueId(m["Trigger Event"])(u.z.object({event:d.blueNodeField()})),ke=d.withTypeBlueId(m["Json Patch Entry"])(u.z.object({name:u.z.string().optional(),description:u.z.string().optional(),val:d.blueNodeField().optional(),op:u.z.string().optional(),path:u.z.string().optional()})),q=d.withTypeBlueId(m["Update Document"])(u.z.object({changeset:u.z.array(ke)}));function D(i,e,t="/",n=[]){const o=i.getContracts()??{};for(const[a,r]of Object.entries(o))if(d.BlueNodeTypeSchema.isTypeOf(r,A)){const h=e.nodeToSchemaOutput(r,A).paths??[];for(const p of h)n.push({absPath:P(t,p),contractPath:P(t,`contracts/${a}`)})}for(const[a,r]of Object.entries(i.getProperties()??{}))D(r,e,P(t,a),n);return n}function F(i,e){return i===e||i.startsWith(e.endsWith("/")?e:e+"/")}function Q(i,e){if(!e.length)return i;let t=i.clone();for(const n of e)try{t=d.applyBlueNodePatch(t,n,!0)}catch(o){throw new H(n,o)}return k.deepFreeze(t)}function g(i){return i!=null}function N(i){return i instanceof d.BlueNode}class Be{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 a=e-1>>1,r=t[a];if(n(o,r)>=0)break;t[e]=r,e=a}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,a=t[e];for(;e<o;){let r=(e<<1)+1;const s=r+1;if(s<this.length&&n(t[s],t[r])<0&&(r=s),n(t[r],a)>=0)break;t[e]=t[r],e=r}t[e]=a}}const Ne=(i,e,t,n,o,a)=>[-i,e,t,n,o,a],Ie=(i,e)=>{for(let t=0;t<i.key.length;t++){const n=i.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 Oe{constructor(){l(this,"queue");this.queue=new Be([],Ie)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class xe{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 Me{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 qe=64;class Ae{constructor(e,t,n,o,a){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=a,this.traceManager=new Me}async route(e,t,n,o,a=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),p={...n};return delete p.dispatchPath,this.route(e,h,p,o,a)}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,a)}}const r=P("/",t.join("/")),s=e.get(r);N(s)&&await this.traverseContracts({doc:e,node:s,nodePath:r,event:n,afterTaskId:o,pathSegments:t,inlineDepth:a})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:a,afterTaskId:r,pathSegments:s,inlineDepth:c}=e;if(!this.shouldSkipForChannel(a,o))for(const[h,p]of Object.entries(n.getContracts()??{})){if(!p.getType())continue;const f=this.registry.get(p.getType());if(!f){console.warn(`No processor registered for contract: ${h}`);continue}const w={nodePath:o,contractName:h,contractNode:p,event:a},y=new L(()=>t,w,this.blue);if(f.supports(a,p,y,h))switch(f.role){case"adapter":await this.processAdapter({cp:f,event:a,contractNode:p,ctx:y,contractName:h,doc:t,afterTaskId:r,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:p,contractName:h,nodePath:o,event:a,depth:s.length,afterTaskId:r});break}}}async processAdapter(e){var C;const{cp:t,event:n,contractNode:o,ctx:a,contractName:r,doc:s,afterTaskId:c,inlineDepth:h}=e;if(h>=qe)throw new Error("Adapter recursion limit reached");const p=this.traceManager.addHop(n,((C=a.getTaskInfo())==null?void 0:C.nodePath)??"",r);await t.handle(p,o,a,r);const f=await a.flush();if(f.find(T=>T.kind==="patch"))throw new Error(`Contract "${r}" (adapter) attempted to patch the document`);const y=f.filter(T=>T.kind==="event");for(const T of y)await this.route(s,[],T.event,c,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:a,depth:r,afterTaskId:s}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(c),p=t.get("/order"),f=d.isBigNumber(p)?p.toNumber():0,w=this.getNextTaskId()+s,y=Ne(r,a.seq,h,f,n,w),C=this.traceManager.addHop(a,o,n);this.queue.push({key:y,nodePath:o,contractName:n,contractNode:t,event:C})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const ze=(i,e,t)=>{(t instanceof H||t instanceof X)&&console.error(`[Blue] Failed to apply patches for contract "${i}" on event ${JSON.stringify(e)}`,t)};function K(i,e){const t=i.clone(),n=o=>{var r;if(!N(o))return;const a=o.getContracts();a&&(!a.checkpoint||((r=a.checkpoint.getType())==null?void 0:r.getBlueId())!==m["Channel Event Checkpoint"])&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:m["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const a=t.get(o);N(a)&&n(a)}return k.deepFreeze(t)}class G{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",m["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 handle(e,t,n){var r;if(!e.channelName||!((r=e.rootEvent)!=null&&r.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),a=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(a,e,o)}init(){return[]}}const U=(i,e)=>i.get(e)!==void 0;class De{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:a}of this.firstSeen.values()){if(!o.channelName)continue;const r=P(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${r}/blueId`;U(e,r)?t.push({op:U(e,s)?"replace":"add",path:s,val:a}):t.push({op:"add",path:r,val:{blueId:a}})}return t}clear(){this.firstSeen.clear()}}class B{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}init(){return[]}}class ee extends B{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",m["Composite Timeline Channel"])}supports(t,n,o){const a=o.getBlue().nodeToSchemaOutput(n,Se);return!a.channels||!t.channelName?!1:a.channels.includes(t.channelName)}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class te extends B{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",m["Document Update Channel"])}supports(t,n,o,a){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,Pe),s=t.payload.path;if(!s||t.channelName===a)return!1;const c=r.path;return k.isNonNullable(c)&&s===o.resolvePath(c)}handle(t,n,o,a){const r=t.payload;r&&o.emitEvent({payload:r,channelName:a,source:"channel"})}}class ne extends B{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",m["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,R);return g(t.originNodePath)&&g(a.path)&&t.originNodePath===o.resolvePath(a.path)}handle(t,n,o,a){const r=o.getBlue().nodeToSchemaOutput(n,R),{originNodePath:s,payload:c}=t;g(r.path)&&s===o.resolvePath(r.path)&&o.emitEvent({payload:c,channelName:a,source:"channel"})}}const v={"MyOS Timeline Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","MyOS Timeline Entry":"uDxZ7dr6Eo2MkKoutP5qxkh3uxQCS1VAptiCPc2R7B7f","MyOS Agent":"AgentBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Channel":"AgentCh4nn3lBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Event":"AgentEv3ntBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V"},$e=d.withTypeBlueId(v["MyOS Timeline Channel"])(Y.extend({account:u.z.string().optional(),email:u.z.string().optional()})),je=d.withTypeBlueId(v["MyOS Timeline Entry"])(O.extend({account:u.z.string().optional(),email:u.z.string().optional()})),Ve=d.withTypeBlueId(v["MyOS Agent"])(u.z.object({agentId:u.z.string().optional()})),We=d.withTypeBlueId(v["MyOS Agent Channel"])(I.extend({agent:Ve.optional(),event:d.blueNodeField().optional()})),Re=d.withTypeBlueId(v["MyOS Agent Event"])(u.z.object({agentId:u.z.string().optional(),id:u.z.number().optional(),timestamp:u.z.number().optional(),event:d.blueNodeField().optional()})),J=i=>i.payload.type==="Timeline Entry"||i.payload.type==="MyOS Timeline Entry";class oe extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",v["MyOS Timeline Channel"])}supports(t,n,o){if(!this.baseSupports(t)||!J(t))return!1;const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,je),c=o.getBlue().nodeToSchemaOutput(n,$e),h=g(c.timelineId)&&g(s.timelineId),p=g(c.account)&&g(s.account),f=g(c.email)&&g(s.email);return h&&s.timelineId===c.timelineId||p&&s.account===c.account||f&&s.email===c.email}handle(t,n,o,a){J(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class ae extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",v["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:a,myosAgentChannel:r}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(a,r)&&this.isEventPatternMatch(a,r,o)}catch(a){return console.warn("Error in MyOSAgentChannelProcessor.supports:",a),!1}}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}parseEventAndChannel(t,n,o){const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,Re),c=a.nodeToSchemaOutput(n,We);return{myosAgentEvent:s,myosAgentChannel:c}}isAgentMatch(t,n){var r;const o=t.agentId,a=(r=n.agent)==null?void 0:r.agentId;return g(o)&&g(a)&&o===a}isEventPatternMatch(t,n,o){const a=n.event;if(!a)return!0;const r=t.event;if(!r)return!1;try{const s=o.getBlue(),c=s.nodeToJson(r),h=s.nodeToJson(a);return k.deepContains(c,h)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class re{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",m.Operation);l(this,"role","adapter")}supports(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,Te),s=this.parseEventPayload(e,n);return g(s==null?void 0:s.operation)&&s.operation===o&&e.source==="channel"&&e.channelName===r.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}init(){return[]}parseEventPayload(e,t){const n=t.getBlue(),o=n.jsonValueToNode(e.payload);if(d.BlueNodeTypeSchema.isTypeOf(o,O)){const a=n.nodeToSchemaOutput(o,O);if(a.message)return n.nodeToSchemaOutput(a.message,ve)}return null}}class se{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",m["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,A);for(const a of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(a)})}init(){return[]}}const ie=!process.env.SKIP_ISOLATED_VM;let S=null;if(ie)try{S=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function Z(i){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(i)||/\bexport\s+/.test(i)}class ce{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!S||!ie?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(s=>t[s])))(...o.map(s=>t[s]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new W(e,o):new V(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!S)throw new Error("isolated-vm not available");const a=new S.Isolate({memoryLimit:32}),r=await a.createContext(),s=r.global;try{await this.setupIsolateEnvironment(s,t);const c=new Map,h=this.createModuleResolver(a,r,c,n);return Z(e)?await this.evaluateESModule(a,r,e,o,h):await this.evaluateSimpleScript(a,r,e,t,o)}catch(c){throw o.isCodeBlock?new W(e,c):new V(e,c)}finally{r.release(),a.dispose()}}static async setupIsolateEnvironment(e,t){if(!S)throw new Error("isolated-vm not available");const n=new S.Callback((...o)=>console.log(...o));await e.set("log",n);for(const[o,a]of Object.entries(t))typeof a=="function"?await e.set(o,new S.Callback(a)):await e.set(o,new S.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async a=>{if(n.has(a))return n.get(a);if(a.startsWith("blue:")){const r=a.slice(5),s=o.loadBlueContent;if(typeof s!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${a})`);const c=await s(r),h=await e.compileModule(c);return n.set(a,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(a)){let r;if(typeof o.loadExternalModule=="function")r=await o.loadExternalModule(a);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${a})`);const s=await e.compileModule(r);return n.set(a,s),await s.instantiate(t,this.createModuleResolver(e,t,n,o)),s}throw new Error(`Unsupported module specifier "${a}"`)}}static async evaluateSimpleScript(e,t,n,o,a){const r=Object.keys(o).join(", "),s=Object.keys(o).map(p=>p),c=`(async (${r}) => { ${a.isCodeBlock?n:`return (${n});`} })(${s.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:a.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,a){let r=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,p=(n.match(h)||[]).join(`
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var ie=(c,e,t)=>e in c?ce(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var l=(c,e,t)=>ie(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@blue-repository/core-dev"),g=require("@blue-labs/language"),C=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),le=(c,e)=>({on:(t,n)=>({end:()=>n(null)})});async function ue(c){return new Promise((e,t)=>{le().on("error",t).end()})}const S=(...c)=>c.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<c.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class U{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 ue()}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 _ 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 M extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class q extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(c,e,t="/",n=[]){const o=c.getContracts()??{};for(const[r,a]of Object.entries(o))if(g.BlueNodeTypeSchema.isTypeOf(a,h.ProcessEmbeddedSchema)){const u=e.nodeToSchemaOutput(a,h.ProcessEmbeddedSchema).paths??[];for(const d of u)n.push({absPath:S(t,d),contractPath:S(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(c.getProperties()??{}))B(a,e,S(t,r),n);return n}function $(c,e){return c===e||c.startsWith(e.endsWith("/")?e:e+"/")}function A(c,e){if(!e.length)return c;let t=c.clone();for(const n of e)try{t=g.applyBlueNodePatch(t,n,!0)}catch(o){throw new J(n,o)}return C.deepFreeze(t)}function y(c){return c!=null}function N(c){return c instanceof g.BlueNode}class he{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 s=a+1;if(s<this.length&&n(t[s],t[a])<0&&(a=s),n(t[a],r)>=0)break;t[e]=t[a],e=a}t[e]=r}}const de=(c,e,t,n,o,r)=>[-c,e,t,n,o,r],pe=(c,e)=>{for(let t=0;t<c.key.length;t++){const n=c.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 me{constructor(){l(this,"queue");this.queue=new he([],pe)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class fe{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 ye{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 ge=64;class Ee{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 ye}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 u=n.dispatchPath.split("/").filter(Boolean),d={...n};return delete d.dispatchPath,this.route(e,u,d,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const u=((i=n.originNodePath)==null?void 0:i.split("/").filter(Boolean))??[];return this.route(e,u,n,o,r)}}const a=S("/",t.join("/")),s=e.get(a);N(s)&&await this.traverseContracts({doc:e,node:s,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:s,inlineDepth:i}=e;if(!this.shouldSkipForChannel(r,o))for(const[u,d]of Object.entries(n.getContracts()??{})){if(!d.getType())continue;const p=this.registry.get(d.getType());if(!p){console.warn(`No processor registered for contract: ${u}`);continue}const m={nodePath:o,contractName:u,contractNode:d,event:r},f=new U(()=>t,m,this.blue);if(p.supports(r,d,f,u))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:d,ctx:f,contractName:u,doc:t,afterTaskId:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:d,contractName:u,nodePath:o,event:r,depth:s.length,afterTaskId:a});break}}}async processAdapter(e){var w;const{cp:t,event:n,contractNode:o,ctx:r,contractName:a,doc:s,afterTaskId:i,inlineDepth:u}=e;if(u>=ge)throw new Error("Adapter recursion limit reached");const d=this.traceManager.addHop(n,((w=r.getTaskInfo())==null?void 0:w.nodePath)??"",a);await t.handle(d,o,r,a);const p=await r.flush();if(p.find(T=>T.kind==="patch"))throw new Error(`Contract "${a}" (adapter) attempted to patch the document`);const f=p.filter(T=>T.kind==="event");for(const T of f)await this.route(s,[],T.event,i,u+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:a,afterTaskId:s}=e,i=t.getType();if(!i){console.warn(`Contract node type is not defined for: ${n}`);return}const u=this.registry.orderOf(i),d=t.get("/order"),p=g.isBigNumber(d)?d.toNumber():0,m=this.getNextTaskId()+s,f=de(a,r.seq,u,p,n,m),w=this.traceManager.addHop(r,o,n);this.queue.push({key:f,nodePath:o,contractName:n,contractNode:t,event:w})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const we=(c,e,t)=>{(t instanceof J||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${c}" on event ${JSON.stringify(e)}`,t)};function D(c,e){const t=c.clone(),n=o=>{if(!N(o))return;const r=o.getContracts();r&&(!r.checkpoint||!g.BlueNodeTypeSchema.isTypeOf(r.checkpoint,h.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:h.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of B(t,e)){const r=t.get(o);N(r)&&n(r)}return C.deepFreeze(t)}class R{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",h.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 handle(e,t,n){var a;if(!e.channelName||!((a=e.rootEvent)!=null&&a.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}init(){return[]}}const W=(c,e)=>c.get(e)!==void 0;class ve{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),s=`${a}/blueId`;W(e,a)?t.push({op:W(e,s)?"replace":"add",path:s,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"}init(){return[]}}class V extends k{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",h.blueIds["Composite Timeline Channel"])}supports(t,n,o){const r=o.getBlue().nodeToSchemaOutput(n,h.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 L extends k{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",h.blueIds["Document Update Channel"])}supports(t,n,o,r){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,h.DocumentUpdateChannelSchema),s=t.payload.path;if(!s||t.channelName===r)return!1;const i=a.path;return C.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){const a=t.payload;a&&o.emitEvent({payload:a,channelName:r,source:"channel"})}}class H extends k{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",h.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema);return y(t.originNodePath)&&y(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema),{originNodePath:s,payload:i}=t;y(a.path)&&s===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}const x=c=>c.payload.type==="Timeline Entry"||c.payload.type==="MyOS Timeline Entry";class Q extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var f;if(!this.baseSupports(t)||!x(t))return!1;const r=o.getBlue(),a=r.jsonValueToNode(t.payload),s=r.nodeToSchemaOutput(a,P.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),u=(f=s.timeline)==null?void 0:f.getValue(),d=y(i.timelineId)&&y(u),p=y(i.account)&&y(s.account),m=y(i.email)&&y(s.email);return d&&u===i.timelineId||p&&s.account===i.account||m&&s.email===i.email}handle(t,n,o,r){x(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class K 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.jsonValueToNode(t.payload),s=r.nodeToSchemaOutput(a,P.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var a;const o=t.agentId,r=(a=n.agent)==null?void 0:a.agentId;return y(o)&&y(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 s=o.getBlue(),i=s.nodeToJson(a),u=s.nodeToJson(r);return C.deepContains(i,u)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class z{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",h.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const a=n.getBlue().nodeToSchemaOutput(t,h.OperationSchema),s=this.parseEventPayload(e,n);return y(s==null?void 0:s.operation)&&s.operation===o&&e.source==="channel"&&e.channelName===a.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}init(){return[]}parseEventPayload(e,t){const n=t.getBlue(),o=n.jsonValueToNode(e.payload);if(g.BlueNodeTypeSchema.isTypeOf(o,h.TimelineEntrySchema)){const r=n.nodeToSchemaOutput(o,h.TimelineEntrySchema);if(r.message)return n.nodeToSchemaOutput(r.message,h.OperationRequestSchema)}return null}}class X{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",h.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}init(){return[]}}const G=!process.env.SKIP_ISOLATED_VM;let v=null;if(G)try{v=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function j(c){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(c)||/\bexport\s+/.test(c)}class Y{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!v||!G?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(j(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(s=>t[s])))(...o.map(s=>t[s]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new q(e,o):new M(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!v)throw new Error("isolated-vm not available");const r=new v.Isolate({memoryLimit:32}),a=await r.createContext(),s=a.global;try{await this.setupIsolateEnvironment(s,t);const i=new Map,u=this.createModuleResolver(r,a,i,n);return j(e)?await this.evaluateESModule(r,a,e,o,u):await this.evaluateSimpleScript(r,a,e,t,o)}catch(i){throw o.isCodeBlock?new q(e,i):new M(e,i)}finally{a.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!v)throw new Error("isolated-vm not available");const n=new v.Callback((...o)=>console.log(...o));await e.set("log",n);for(const[o,r]of Object.entries(t))typeof r=="function"?await e.set(o,new v.Callback(r)):await e.set(o,new v.ExternalCopy(r).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),s=o.loadBlueContent;if(typeof s!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const i=await s(a),u=await e.compileModule(i);return n.set(r,u),await u.instantiate(t,this.createModuleResolver(e,t,n,o)),u}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 s=await e.compileModule(a);return n.set(r,s),await s.instantiate(t,this.createModuleResolver(e,t,n,o)),s}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const a=Object.keys(o).join(", "),s=Object.keys(o).map(d=>d),i=`(async (${a}) => { ${r.isCodeBlock?n:`return (${n});`} })(${s.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 u=/^\s*(import\s.+?;|export\s.+?;)/gm,d=(n.match(u)||[]).join(`
|
|
2
|
+
`),p=n.replace(u,"").trim();a=`
|
|
3
|
+
${d}
|
|
4
4
|
const run = function() {
|
|
5
|
-
${
|
|
5
|
+
${p}
|
|
6
6
|
};
|
|
7
7
|
export default run();
|
|
8
|
-
`}const s=await e.compileModule(
|
|
8
|
+
`}const s=await e.compileModule(a);return await s.instantiate(t,r),await s.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await s.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}}class Z{static createStandardBindings(e,t,n){const o=e.getBlue();return{document:r=>{const a=e.get(r);return g.isBigNumber(a)?a.toNumber():N(a)?o.nodeToJson(a,"original"):a},event:t.payload,steps:n}}}class Se{constructor(){l(this,"stepType","Update Document")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema)}async evaluateChangeValue(e,t,n,o){const r=e==null?void 0:e.getValue();if(typeof r=="string"&&r.startsWith("${")&&r.endsWith("}")){const a=r.slice(2,-1);return await Y.evaluate({code:a,ctx:t,bindings:Z.createStandardBindings(t,n,o)})}return e}async execute(e,t,n,o,r){if(!g.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema))return;const a=n.getBlue().nodeToSchemaOutput(e,h.UpdateDocumentSchema);for(const s of a.changeset??[])if(s.path){if(s.op==="replace"||s.op==="add"){const i=await this.evaluateChangeValue(s.val,n,t,r);n.addPatch({op:s.op,path:s.path,val:i}),n.emitEvent({payload:{type:"Document Update",op:s.op,path:n.resolvePath(s.path),val:i}})}s.op==="remove"&&(n.addPatch({op:s.op,path:s.path}),n.emitEvent({payload:{type:"Document Update",op:s.op,path:n.resolvePath(s.path),val:null}}))}}}class Te{constructor(){l(this,"stepType","Trigger Event")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!g.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,h.TriggerEventSchema);if(!r.event)return;const a=o.nodeToJson(r.event,"original");n.emitEvent({payload:a})}}class be{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!g.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema))return;const s=n.getBlue().nodeToSchemaOutput(e,h.JavaScriptCodeSchema);if(!s.code)throw new Error("JavaScript code is required");const i=await Y.evaluate({code:s.code,ctx:n,bindings:Z.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(i&&typeof i=="object"&&"events"in i){const u=i;if(Array.isArray(u.events))for(const d of u.events)n.emitEvent({payload:d})}return i}}const Pe=[new Se,new Te,new be];class I{constructor(e=Pe){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",h.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,h.SequentialWorkflowSchema).channel;return e.source==="channel"&&e.channelName===a}async handle(e,t,n,o){var s;const r={},a=(s=t.getProperties())==null?void 0:s.steps.getItems();for(const[i,u]of(a??[]).entries()){const d=this.executors.find(m=>m.supports(u));if(!d)throw new Error(`Unsupported workflow step type "${u.getType()}"`);const p=await d.execute(u,e,n,o,r);if(p!==void 0){const m=u.getName(),f=typeof m=="string"?m:`Step${i+1}`;r[f]=p}await n.flush()}}init(){return[]}}class ee{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",h.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new I}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowOperationSchema).operation,s=e.channelName;return e.source==="channel"&&C.isNonNullable(s)&&C.isNonNullable(a)&&s===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 F=c=>c.payload.type==="Timeline Entry";class te extends k{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",h.blueIds["Timeline Channel"])}supports(t,n,o){var d;if(!this.baseSupports(t)||!F(t))return!1;const r=o.getBlue(),a=r.nodeToSchemaOutput(r.jsonValueToNode(t.payload),h.TimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,h.TimelineChannelSchema),i=(d=a.timeline)==null?void 0:d.getValue();return y(s.timelineId)&&y(i)&&i===s.timelineId}handle(t,n,o,r){F(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const Ce=[new X,new H,new L,new te,new Q,new K,new V,new z,new I,new ee];class ke{constructor(e,t=Ce){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new ve);this.blue=e,this.registry=new fe(t),this.queue=new me,this.router=new Ee(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new R(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialise(e){e=D(e,this.blue);const t=await this.bootstrapContracts(e);for(const n of t)await this.router.route(e,[],n,0);return this.drainQueue(e)}async processEvents(e,t){let n=D(e,this.blue);const o=[];for(const r of t)try{const a={payload:r,source:"external"};await this.router.route(n,[],a,0);const s=await this.drainQueue(n);n=s.state,o.push(...s.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=A(n,i))}finally{this.checkpointCache.clear()}return{state:n,emitted:o}}async bootstrapContracts(e){const t=[],n=e.getContracts();if(!n)return t;for(const[,o]of Object.entries(n)){const r=this.registry.get(o.getType());r!=null&&r.init&&t.push(...await r.init(o))}return t}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 s=this.queue.pop(),{nodePath:i,contractName:u,contractNode:d,event:p}=s,m=t.get(i);if(!N(m)||!((a=m.getContracts())!=null&&a[u])||!d.getType())continue;const f=this.registry.get(d.getType());if(!f){console.warn(`No processor registered for contract: ${u}`);continue}const w=new U(()=>t,s,this.blue,async T=>{for(const E of T)if(E.kind==="patch"){const ne=B(t,this.blue);for(const b of ne){const oe=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],O=w.getNodePath(),re=oe.some(se=>$(se,b.absPath)),ae=$(O,b.absPath);if(re&&!ae)throw new _(E.patch,b.absPath,O)}try{t=A(t,[E.patch])}catch(b){throw we(u,p,b),b}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,s.key[5]))});await f.handle(p,d,w,u),await w.flush()}return{state:t,emitted:n}}}exports.BlueDocumentProcessor=ke;exports.ChannelEventCheckpointProcessor=R;exports.CompositeTimelineChannelProcessor=V;exports.DocumentUpdateChannelProcessor=L;exports.EmbeddedNodeChannelProcessor=H;exports.MyOSAgentChannelProcessor=K;exports.MyOSTimelineChannelProcessor=Q;exports.OperationProcessor=z;exports.ProcessEmbeddedProcessor=X;exports.SequentialWorkflowOperationProcessor=ee;exports.SequentialWorkflowProcessor=I;exports.TimelineChannelProcessor=te;
|