@blue-labs/document-processor 1.26.1 → 1.27.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 CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var he=Object.defineProperty;var de=(c,e,t)=>e in c?he(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var l=(c,e,t)=>de(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@blue-repository/core-dev"),f=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),pe=(c,e)=>({on:(t,n)=>({end:()=>n(null)})});async function me(c){return new Promise((e,t)=>{pe().on("error",t).end()})}const b=(...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 z{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=b(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:b(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 b(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 me()}loadBlueContent(e){throw new Error("Not implemented")}}class L 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 $ extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class A extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function O(c,e,t="/",n=[]){const o=c.getContracts()??{};for(const[r,a]of Object.entries(o))if(f.BlueNodeTypeSchema.isTypeOf(a,d.ProcessEmbeddedSchema)){const u=e.nodeToSchemaOutput(a,d.ProcessEmbeddedSchema).paths??[];for(const h of u)n.push({absPath:b(t,h),contractPath:b(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(c.getProperties()??{}))O(a,e,b(t,r),n);return n}function D(c,e){return c===e||c.startsWith(e.endsWith("/")?e:e+"/")}function W(c,e){if(!e.length)return c;let t=c.clone();for(const n of e)try{t=f.applyBlueNodePatch(t,n,!0)}catch(o){throw new L(n,o)}return v.deepFreeze(t)}function y(c){return c!=null}function C(c){return c instanceof f.BlueNode}class fe{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 ye=(c,e,t,n,o,r)=>[-c,e,t,n,o,r],ge=(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 Ee{constructor(){l(this,"queue");this.queue=new fe([],ge)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class ve{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 we{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 Se=64;class be{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 we}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),h={...n};return delete h.dispatchPath,this.route(e,u,h,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=b("/",t.join("/")),s=e.get(a);C(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,h]of Object.entries(n.getContracts()??{})){if(!h.getType())continue;const p=this.registry.get(h.getType());if(!p){console.warn(`No processor registered for contract: ${u}`);continue}const m={nodePath:o,contractName:u,contractNode:h,event:r},g=new z(()=>t,m,this.blue);if(p.supports(r,h,g,u))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:h,ctx:g,contractName:u,doc:t,afterTaskId:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:h,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>=Se)throw new Error("Adapter recursion limit reached");const h=this.traceManager.addHop(n,((w=r.getTaskInfo())==null?void 0:w.nodePath)??"",a);await t.handle(h,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 g=p.filter(T=>T.kind==="event");for(const T of g)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),h=t.get("/order"),p=f.isBigNumber(h)?h.toNumber():0,m=this.getNextTaskId()+s,g=ye(a,r.seq,u,p,n,m),w=this.traceManager.addHop(r,o,n);this.queue.push({key:g,nodePath:o,contractName:n,contractNode:t,event:w})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Te=(c,e,t)=>{(t instanceof L||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${c}" on event ${JSON.stringify(e)}`,t)};function j(c,e){const t=c.clone(),n=o=>{if(!C(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!f.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 O(t,e)){const r=t.get(o);C(r)&&n(r)}return v.deepFreeze(t)}function Pe(c,e){const t=c.clone();return C(t)&&(H(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),v.deepFreeze(t)}function H(c,e){const t=c.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class R{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 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)}}const x=(c,e)=>c.get(e)!==void 0;class Ce{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=b(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${a}/blueId`;x(e,a)?t.push({op:x(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"}}class Q 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 K 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),s=t.payload.get("/path");if(!s||t.channelName===r)return!1;const i=a.path;return v.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 X 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 y(t.originNodePath)&&y(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:s,payload:i}=t;y(a.path)&&s===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}class Y{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class Z 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 s=o.getBlue(),i=s.nodeToJson(t.payload),u=s.nodeToJson(r);return v.deepContains(i,u)}catch(s){return console.warn("Error during lifecycle event pattern matching:",s),!1}}}const J=(c,e)=>{const t=e.getBlue();return t.isTypeOf(c.payload,d.TimelineEntrySchema)||t.isTypeOf(c.payload,P.MyOSTimelineEntrySchema)};class G extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var m;if(!this.baseSupports(t)||!J(t,o))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,P.MyOSTimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),i=(m=a.timeline)==null?void 0:m.timelineId,u=y(s.timelineId)&&y(i),h=y(s.account)&&y(a.account),p=y(s.email)&&y(a.email);return u&&i===s.timelineId||h&&a.account===s.account||p&&a.email===s.email}handle(t,n,o,r){J(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ee 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),s=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:a,myosAgentChannel:s}}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 v.deepContains(i,u)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class te{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),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"})}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 ne{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 oe=!process.env.SKIP_ISOLATED_VM;let S=null;if(oe)try{S=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function F(c){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(c)||/\bexport\s+/.test(c)}class N{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!S||!oe?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(F(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 A(e,o):new $(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!S)throw new Error("isolated-vm not available");const r=new S.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 F(e)?await this.evaluateESModule(r,a,e,o,u):await this.evaluateSimpleScript(r,a,e,t,o)}catch(i){throw o.isCodeBlock?new A(e,i):new $(e,i)}finally{a.release(),r.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,r]of Object.entries(t))typeof r=="function"?await e.set(o,new S.Callback(r)):await e.set(o,new S.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(h=>h),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,h=(n.match(u)||[]).join(`
2
- `),p=n.replace(u,"").trim();a=`
3
- ${h}
1
+ "use strict";var he=Object.defineProperty;var de=(c,e,t)=>e in c?he(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var l=(c,e,t)=>de(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@blue-repository/core-dev"),f=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),pe=(c,e)=>({on:(t,n)=>({end:()=>n(null)})});async function me(c){return new Promise((e,t)=>{pe().on("error",t).end()})}const b=(...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 z{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=b(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:b(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 b(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 me()}loadBlueContent(e){throw new Error("Not implemented")}}class L 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 $ extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class A extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function O(c,e,t="/",n=[]){const o=c.getContracts()??{};for(const[r,a]of Object.entries(o))if(f.BlueNodeTypeSchema.isTypeOf(a,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(a,d.ProcessEmbeddedSchema).paths??[];for(const u of h)n.push({absPath:b(t,u),contractPath:b(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(c.getProperties()??{}))O(a,e,b(t,r),n);return n}function D(c,e){return c===e||c.startsWith(e.endsWith("/")?e:e+"/")}function W(c,e){if(!e.length)return c;let t=c.clone();for(const n of e)try{t=f.applyBlueNodePatch(t,n,!0)}catch(o){throw new L(n,o)}return v.deepFreeze(t)}function y(c){return c!=null}function C(c){return c instanceof f.BlueNode}class fe{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 ye=(c,e,t,n,o,r)=>[-c,e,t,n,o,r],ge=(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 Ee{constructor(){l(this,"queue");this.queue=new fe([],ge)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class ve{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 we{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 Se=64;class be{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 we}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=b("/",t.join("/")),s=e.get(a);C(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[h,u]of Object.entries(n.getContracts()??{})){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${h}`);continue}const m={nodePath:o,contractName:h,contractNode:u,event:r},g=new z(()=>t,m,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:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,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:h}=e;if(h>=Se)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((w=r.getTaskInfo())==null?void 0:w.nodePath)??"",a);await t.handle(u,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 g=p.filter(T=>T.kind==="event");for(const T of g)await this.route(s,[],T.event,i,h+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 h=this.registry.orderOf(i),u=t.get("/order"),p=f.isBigNumber(u)?u.toNumber():0,m=this.getNextTaskId()+s,g=ye(a,r.seq,h,p,n,m),w=this.traceManager.addHop(r,o,n);this.queue.push({key:g,nodePath:o,contractName:n,contractNode:t,event:w})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Te=(c,e,t)=>{(t instanceof L||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${c}" on event ${JSON.stringify(e)}`,t)};function j(c,e){const t=c.clone(),n=o=>{if(!C(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!f.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 O(t,e)){const r=t.get(o);C(r)&&n(r)}return v.deepFreeze(t)}function Pe(c,e){const t=c.clone();return C(t)&&(H(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),v.deepFreeze(t)}function H(c,e){const t=c.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class R{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 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)}}const x=(c,e)=>c.get(e)!==void 0;class Ce{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=b(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${a}/blueId`;x(e,a)?t.push({op:x(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"}}class Q 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 K 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),s=t.payload.get("/path");if(!s||t.channelName===r)return!1;const i=a.path;return v.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 X 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 y(t.originNodePath)&&y(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:s,payload:i}=t;y(a.path)&&s===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}class Y{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class Z 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 s=o.getBlue(),i=s.nodeToJson(t.payload),h=s.nodeToJson(r);return v.deepContains(i,h)}catch(s){return console.warn("Error during lifecycle event pattern matching:",s),!1}}}const J=(c,e)=>{const t=e.getBlue();return t.isTypeOf(c.payload,d.TimelineEntrySchema)||t.isTypeOf(c.payload,P.MyOSTimelineEntrySchema)};class G extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var m;if(!this.baseSupports(t)||!J(t,o))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,P.MyOSTimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),i=(m=a.timeline)==null?void 0:m.timelineId,h=y(s.timelineId)&&y(i),u=y(s.account)&&y(a.account),p=y(s.email)&&y(a.email);return h&&i===s.timelineId||u&&a.account===s.account||p&&a.email===s.email}handle(t,n,o,r){J(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ee 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),s=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:a,myosAgentChannel:s}}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),h=s.nodeToJson(r);return v.deepContains(i,h)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class te{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),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"})}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 ne{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 oe=!process.env.SKIP_ISOLATED_VM;let S=null;if(oe)try{S=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function F(c){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(c)||/\bexport\s+/.test(c)}class N{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!S||!oe?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(F(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 A(e,o):new $(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!S)throw new Error("isolated-vm not available");const r=new S.Isolate({memoryLimit:32}),a=await r.createContext(),s=a.global;try{await this.setupIsolateEnvironment(s,t);const i=new Map,h=this.createModuleResolver(r,a,i,n);let u;return F(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 A(e,i):new $(e,i)}finally{a.release(),r.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,r]of Object.entries(t))typeof r=="function"?await e.set(o,new S.Callback(r)):await e.set(o,new S.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),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 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(u=>u),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 h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
2
+ `),p=n.replace(h,"").trim();a=`
3
+ ${u}
4
4
  const run = function() {
5
5
  ${p}
6
6
  };
7
7
  export default run();
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 B{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),a=f.isBigNumber(r)?r.toNumber():r;return{document:s=>{const i=e.get(s);return f.isBigNumber(i)?i.toNumber():C(i)?o.nodeToJson(i,"original"):i},event:a,steps:n}}}function U(c,e){const{op:t,path:n,val:o,from:r}=c;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 ke(c){return c.jsonValueToNode({type:"Document Processing Initiated"})}class Ie{constructor(){l(this,"stepType","Update Document")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const a=n.getBlue();if(!f.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const s=await this.evaluateChangeset(e.get("/changeset"),n,t,r),i=f.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:s}),u=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const h of u.changeset??[]){if(!h.path)continue;const p=h.val;if((h.op==="replace"||h.op==="add")&&v.isNonNullable(p)){const m=await this.evaluateChangeValue(p,n,t,r);n.addPatch({op:h.op,path:h.path,val:m}),n.emitEvent({payload:U({op:h.op,path:n.resolvePath(h.path),val:a.nodeToJson(m,"original")},a)})}h.op==="remove"&&(n.addPatch({op:h.op,path:h.path}),n.emitEvent({payload:U({op:h.op,path:n.resolvePath(h.path),val:null},a)}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(typeof e=="string"&&e.startsWith("${")&&e.endsWith("}")){const a=e.slice(2,-1),s=await N.evaluate({code:a,ctx:t,bindings:B.createStandardBindings(t,n,o)});return r.jsonValueToNode(s??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(typeof r=="string"&&r.startsWith("${")&&r.endsWith("}")){const s=r.slice(2,-1),i=await N.evaluate({code:s,ctx:t,bindings:B.createStandardBindings(t,n,o)});return a.jsonValueToNode(i??null)}return e}}class Ne{constructor(){l(this,"stepType","Trigger Event")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!f.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,d.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event})}}class Be{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!f.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const a=n.getBlue(),s=a.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!s.code)throw new Error("JavaScript code is required");const i=await N.evaluate({code:s.code,ctx:n,bindings:B.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 h of u.events)n.emitEvent({payload:a.jsonValueToNode(Oe(h))})}return i}}function Oe(c){return JSON.parse(JSON.stringify(c))}const Me=[new Ie,new Ne,new Be];class M{constructor(e=Me){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 s;const r={},a=(s=t.getProperties())==null?void 0:s.steps.getItems();for(const[i,u]of(a??[]).entries()){const h=this.executors.find(m=>m.supports(u));if(!h)throw new Error(`Unsupported workflow step type "${u.getType()}"`);const p=await h.execute(u,e,n,o,r);if(p!==void 0){const m=u.getName(),g=typeof m=="string"?m:`Step${i+1}`;r[g]=p}await n.flush()}}}class re{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 M}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,s=e.channelName;return e.source==="channel"&&v.isNonNullable(s)&&v.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 V=c=>f.BlueNodeTypeSchema.isTypeOf(c.payload,d.TimelineEntrySchema);class ae extends k{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",d.blueIds["Timeline Channel"])}supports(t,n,o){var h;if(!this.baseSupports(t)||!V(t))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(h=a.timeline)==null?void 0:h.timelineId;return y(s.timelineId)&&y(i)&&i===s.timelineId}handle(t,n,o,r){V(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const qe=[new ne,new X,new K,new ae,new G,new ee,new Q,new Z,new te,new M,new re,new Y];class $e{constructor(e,t=qe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Ce);this.blue=e,this.registry=new ve(t),this.queue=new Ee,this.router=new be(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 initialize(e){let t=j(e,this.blue);const n={payload:ke(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=Pe(t,this.blue),{state:t,emitted:o}}async processEvents(e,t){let n=j(e,this.blue);const o=[];if(!H(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 s=await this.drainQueue(n);n=s.state,o.push(...s.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=W(n,i))}finally{this.checkpointCache.clear()}return{state: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 s=this.queue.pop(),{nodePath:i,contractName:u,contractNode:h,event:p}=s,m=t.get(i);if(!C(m)||!((a=m.getContracts())!=null&&a[u])||!h.getType())continue;const g=this.registry.get(h.getType());if(!g){console.warn(`No processor registered for contract: ${u}`);continue}const w=new z(()=>t,s,this.blue,async T=>{for(const E of T)if(E.kind==="patch"){const se=O(t,this.blue);for(const I of se){const ce=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],q=w.getNodePath(),ie=ce.some(ue=>D(ue,I.absPath)),le=D(q,I.absPath);if(ie&&!le)throw new _(E.patch,I.absPath,q)}try{t=W(t,[E.patch])}catch(I){throw Te(u,p,I),I}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,s.key[5]))});await g.handle(p,h,w,u),await w.flush()}return{state:t,emitted:n}}}exports.BlueDocumentProcessor=$e;exports.ChannelEventCheckpointProcessor=R;exports.CompositeTimelineChannelProcessor=Q;exports.DocumentUpdateChannelProcessor=K;exports.EmbeddedNodeChannelProcessor=X;exports.InitializedMarkerProcessor=Y;exports.LifecycleEventChannelProcessor=Z;exports.MyOSAgentChannelProcessor=ee;exports.MyOSTimelineChannelProcessor=G;exports.OperationProcessor=te;exports.ProcessEmbeddedProcessor=ne;exports.SequentialWorkflowOperationProcessor=re;exports.SequentialWorkflowProcessor=M;exports.TimelineChannelProcessor=ae;
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})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class B{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),a=f.isBigNumber(r)?r.toNumber():r;return{document:s=>{const i=e.get(s);return f.isBigNumber(i)?i.toNumber():C(i)?o.nodeToJson(i,"original"):i},event:a,steps:n}}}function U(c,e){const{op:t,path:n,val:o,from:r}=c;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 ke(c){return c.jsonValueToNode({type:"Document Processing Initiated"})}class Ie{constructor(){l(this,"stepType","Update Document")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const a=n.getBlue();if(!f.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const s=await this.evaluateChangeset(e.get("/changeset"),n,t,r),i=f.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:s}),h=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const u of h.changeset??[]){if(!u.path)continue;const p=u.val;if((u.op==="replace"||u.op==="add")&&v.isNonNullable(p)){const m=await this.evaluateChangeValue(p,n,t,r);n.addPatch({op:u.op,path:u.path,val:m}),n.emitEvent({payload:U({op:u.op,path:n.resolvePath(u.path),val:a.nodeToJson(m,"original")},a)})}u.op==="remove"&&(n.addPatch({op:u.op,path:u.path}),n.emitEvent({payload:U({op:u.op,path:n.resolvePath(u.path),val:null},a)}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(typeof e=="string"&&e.startsWith("${")&&e.endsWith("}")){const a=e.slice(2,-1),s=await N.evaluate({code:a,ctx:t,bindings:B.createStandardBindings(t,n,o)});return r.jsonValueToNode(s??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(typeof r=="string"&&r.startsWith("${")&&r.endsWith("}")){const s=r.slice(2,-1),i=await N.evaluate({code:s,ctx:t,bindings:B.createStandardBindings(t,n,o)});return a.jsonValueToNode(i??null)}return e}}class Ne{constructor(){l(this,"stepType","Trigger Event")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!f.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,d.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event})}}class Be{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return f.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!f.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const a=n.getBlue(),s=a.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!s.code)throw new Error("JavaScript code is required");const i=await N.evaluate({code:s.code,ctx:n,bindings:B.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 Oe=[new Ie,new Ne,new Be];class M{constructor(e=Oe){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 s;const r={},a=(s=t.getProperties())==null?void 0:s.steps.getItems();for(const[i,h]of(a??[]).entries()){const u=this.executors.find(m=>m.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 m=h.getName(),g=typeof m=="string"?m:`Step${i+1}`;r[g]=p}await n.flush()}}}class re{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 M}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,s=e.channelName;return e.source==="channel"&&v.isNonNullable(s)&&v.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 V=c=>f.BlueNodeTypeSchema.isTypeOf(c.payload,d.TimelineEntrySchema);class ae 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)||!V(t))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(u=a.timeline)==null?void 0:u.timelineId;return y(s.timelineId)&&y(i)&&i===s.timelineId}handle(t,n,o,r){V(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const Me=[new ne,new X,new K,new ae,new G,new ee,new Q,new Z,new te,new M,new re,new Y];class qe{constructor(e,t=Me){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Ce);this.blue=e,this.registry=new ve(t),this.queue=new Ee,this.router=new be(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 initialize(e){let t=j(e,this.blue);const n={payload:ke(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=Pe(t,this.blue),{state:t,emitted:o}}async processEvents(e,t){let n=j(e,this.blue);const o=[];if(!H(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 s=await this.drainQueue(n);n=s.state,o.push(...s.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=W(n,i))}finally{this.checkpointCache.clear()}return{state: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 s=this.queue.pop(),{nodePath:i,contractName:h,contractNode:u,event:p}=s,m=t.get(i);if(!C(m)||!((a=m.getContracts())!=null&&a[h])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${h}`);continue}const w=new z(()=>t,s,this.blue,async T=>{for(const E of T)if(E.kind==="patch"){const se=O(t,this.blue);for(const I of se){const ce=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],q=w.getNodePath(),ie=ce.some(ue=>D(ue,I.absPath)),le=D(q,I.absPath);if(ie&&!le)throw new _(E.patch,I.absPath,q)}try{t=W(t,[E.patch])}catch(I){throw Te(h,p,I),I}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,s.key[5]))});await g.handle(p,u,w,h),await w.flush()}return{state:t,emitted:n}}}exports.BlueDocumentProcessor=qe;exports.ChannelEventCheckpointProcessor=R;exports.CompositeTimelineChannelProcessor=Q;exports.DocumentUpdateChannelProcessor=K;exports.EmbeddedNodeChannelProcessor=X;exports.InitializedMarkerProcessor=Y;exports.LifecycleEventChannelProcessor=Z;exports.MyOSAgentChannelProcessor=ee;exports.MyOSTimelineChannelProcessor=G;exports.OperationProcessor=te;exports.ProcessEmbeddedProcessor=ne;exports.SequentialWorkflowOperationProcessor=re;exports.SequentialWorkflowProcessor=M;exports.TimelineChannelProcessor=ae;
package/dist/index.mjs CHANGED
@@ -103,13 +103,13 @@ function W(c, e, t = "/", n = []) {
103
103
  a,
104
104
  $
105
105
  )) {
106
- const u = e.nodeToSchemaOutput(
106
+ const h = e.nodeToSchemaOutput(
107
107
  a,
108
108
  $
109
109
  ).paths ?? [];
110
- for (const h of u)
110
+ for (const u of h)
111
111
  n.push({
112
- absPath: T(t, h),
112
+ absPath: T(t, u),
113
113
  contractPath: T(t, `contracts/${r}`)
114
114
  });
115
115
  }
@@ -371,12 +371,12 @@ class De {
371
371
  var i;
372
372
  if (n.seq === void 0 && (n.seq = this.getNextEventSeq()), t.length === 0) {
373
373
  if (n.dispatchPath) {
374
- const u = n.dispatchPath.split("/").filter(Boolean), h = { ...n };
375
- return delete h.dispatchPath, this.route(e, u, h, o, r);
374
+ const h = n.dispatchPath.split("/").filter(Boolean), u = { ...n };
375
+ return delete u.dispatchPath, this.route(e, h, u, o, r);
376
376
  }
377
377
  if (n.source === "channel" && n.originNodePath && n.originNodePath !== "/") {
378
- const u = ((i = n.originNodePath) == null ? void 0 : i.split("/").filter(Boolean)) ?? [];
379
- return this.route(e, u, n, o, r);
378
+ const h = ((i = n.originNodePath) == null ? void 0 : i.split("/").filter(Boolean)) ?? [];
379
+ return this.route(e, h, n, o, r);
380
380
  }
381
381
  }
382
382
  const a = T("/", t.join("/")), s = e.get(a);
@@ -404,30 +404,30 @@ class De {
404
404
  inlineDepth: i
405
405
  } = e;
406
406
  if (!this.shouldSkipForChannel(r, o))
407
- for (const [u, h] of Object.entries(
407
+ for (const [h, u] of Object.entries(
408
408
  n.getContracts() ?? {}
409
409
  )) {
410
- if (!h.getType()) continue;
411
- const d = this.registry.get(h.getType());
410
+ if (!u.getType()) continue;
411
+ const d = this.registry.get(u.getType());
412
412
  if (!d) {
413
- console.warn(`No processor registered for contract: ${u}`);
413
+ console.warn(`No processor registered for contract: ${h}`);
414
414
  continue;
415
415
  }
416
416
  const p = {
417
417
  nodePath: o,
418
- contractName: u,
419
- contractNode: h,
418
+ contractName: h,
419
+ contractNode: u,
420
420
  event: r
421
421
  }, y = new G(() => t, p, this.blue);
422
- if (d.supports(r, h, y, u))
422
+ if (d.supports(r, u, y, h))
423
423
  switch (d.role) {
424
424
  case "adapter":
425
425
  await this.processAdapter({
426
426
  cp: d,
427
427
  event: r,
428
- contractNode: h,
428
+ contractNode: u,
429
429
  ctx: y,
430
- contractName: u,
430
+ contractName: h,
431
431
  doc: t,
432
432
  afterTaskId: a,
433
433
  inlineDepth: i
@@ -435,8 +435,8 @@ class De {
435
435
  break;
436
436
  case "handler":
437
437
  this.scheduleHandler({
438
- contractNode: h,
439
- contractName: u,
438
+ contractNode: u,
439
+ contractName: h,
440
440
  nodePath: o,
441
441
  event: r,
442
442
  depth: s.length,
@@ -459,16 +459,16 @@ class De {
459
459
  contractName: a,
460
460
  doc: s,
461
461
  afterTaskId: i,
462
- inlineDepth: u
462
+ inlineDepth: h
463
463
  } = e;
464
- if (u >= Ae)
464
+ if (h >= Ae)
465
465
  throw new Error("Adapter recursion limit reached");
466
- const h = this.traceManager.addHop(
466
+ const u = this.traceManager.addHop(
467
467
  n,
468
468
  ((w = r.getTaskInfo()) == null ? void 0 : w.nodePath) ?? "",
469
469
  a
470
470
  );
471
- await t.handle(h, o, r, a);
471
+ await t.handle(u, o, r, a);
472
472
  const d = await r.flush();
473
473
  if (d.find((b) => b.kind === "patch"))
474
474
  throw new Error(
@@ -476,7 +476,7 @@ class De {
476
476
  );
477
477
  const y = d.filter((b) => b.kind === "event");
478
478
  for (const b of y)
479
- await this.route(s, [], b.event, i, u + 1);
479
+ await this.route(s, [], b.event, i, h + 1);
480
480
  }
481
481
  /**
482
482
  * Schedules a handler contract for future execution
@@ -487,10 +487,10 @@ class De {
487
487
  console.warn(`Contract node type is not defined for: ${n}`);
488
488
  return;
489
489
  }
490
- const u = this.registry.orderOf(i), h = t.get("/order"), d = q(h) ? h.toNumber() : 0, p = this.getNextTaskId() + s, y = Oe(
490
+ const h = this.registry.orderOf(i), u = t.get("/order"), d = q(u) ? u.toNumber() : 0, p = this.getNextTaskId() + s, y = Oe(
491
491
  a,
492
492
  r.seq,
493
- u,
493
+ h,
494
494
  d,
495
495
  n,
496
496
  p
@@ -732,8 +732,8 @@ class _e extends P {
732
732
  if (!r)
733
733
  return !0;
734
734
  try {
735
- const s = o.getBlue(), i = s.nodeToJson(t.payload), u = s.nodeToJson(r);
736
- return X(i, u);
735
+ const s = o.getBlue(), i = s.nodeToJson(t.payload), h = s.nodeToJson(r);
736
+ return X(i, h);
737
737
  } catch (s) {
738
738
  return console.warn("Error during lifecycle event pattern matching:", s), !1;
739
739
  }
@@ -755,8 +755,8 @@ class ze extends P {
755
755
  const a = o.getBlue().nodeToSchemaOutput(
756
756
  t.payload,
757
757
  Z
758
- ), s = o.getBlue().nodeToSchemaOutput(n, Se), i = (p = a.timeline) == null ? void 0 : p.timelineId, u = m(s.timelineId) && m(i), h = m(s.account) && m(a.account), d = m(s.email) && m(a.email);
759
- return u && i === s.timelineId || h && a.account === s.account || d && a.email === s.email;
758
+ ), s = o.getBlue().nodeToSchemaOutput(n, Se), i = (p = a.timeline) == null ? void 0 : p.timelineId, h = m(s.timelineId) && m(i), u = m(s.account) && m(a.account), d = m(s.email) && m(a.email);
759
+ return h && i === s.timelineId || u && a.account === s.account || d && a.email === s.email;
760
760
  }
761
761
  handle(t, n, o, r) {
762
762
  z(t, o) && o.emitEvent({
@@ -838,8 +838,8 @@ class He extends P {
838
838
  if (!a)
839
839
  return !1;
840
840
  try {
841
- const s = o.getBlue(), i = s.nodeToJson(a), u = s.nodeToJson(r);
842
- return X(i, u);
841
+ const s = o.getBlue(), i = s.nodeToJson(a), h = s.nodeToJson(r);
842
+ return X(i, h);
843
843
  } catch (s) {
844
844
  return console.warn("Error during event pattern matching:", s), !1;
845
845
  }
@@ -958,25 +958,26 @@ class A {
958
958
  const r = new v.Isolate({ memoryLimit: 32 }), a = await r.createContext(), s = a.global;
959
959
  try {
960
960
  await this.setupIsolateEnvironment(s, t);
961
- const i = /* @__PURE__ */ new Map(), u = this.createModuleResolver(
961
+ const i = /* @__PURE__ */ new Map(), h = this.createModuleResolver(
962
962
  r,
963
963
  a,
964
964
  i,
965
965
  n
966
966
  );
967
- return H(e) ? await this.evaluateESModule(
967
+ let u;
968
+ return H(e) ? u = await this.evaluateESModule(
968
969
  r,
969
970
  a,
970
971
  e,
971
972
  o,
972
- u
973
- ) : await this.evaluateSimpleScript(
973
+ h
974
+ ) : u = await this.evaluateSimpleScript(
974
975
  r,
975
976
  a,
976
977
  e,
977
978
  t,
978
979
  o
979
- );
980
+ ), this.deepClone(u);
980
981
  } catch (i) {
981
982
  throw o.isCodeBlock ? new V(e, i) : new J(e, i);
982
983
  } finally {
@@ -1010,11 +1011,11 @@ class A {
1010
1011
  throw new Error(
1011
1012
  `ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`
1012
1013
  );
1013
- const i = await s(a), u = await e.compileModule(i);
1014
- return n.set(r, u), await u.instantiate(
1014
+ const i = await s(a), h = await e.compileModule(i);
1015
+ return n.set(r, h), await h.instantiate(
1015
1016
  t,
1016
1017
  this.createModuleResolver(e, t, n, o)
1017
- ), u;
1018
+ ), h;
1018
1019
  }
1019
1020
  if (/^https?:\/\//.test(r)) {
1020
1021
  let a;
@@ -1037,7 +1038,7 @@ class A {
1037
1038
  * Evaluate code as a simple script (no imports/exports)
1038
1039
  */
1039
1040
  static async evaluateSimpleScript(e, t, n, o, r) {
1040
- const a = Object.keys(o).join(", "), s = Object.keys(o).map((h) => h), i = `(async (${a}) => { ${r.isCodeBlock ? n : `return (${n});`} })(${s.join(", ")})`;
1041
+ const a = Object.keys(o).join(", "), s = Object.keys(o).map((u) => u), i = `(async (${a}) => { ${r.isCodeBlock ? n : `return (${n});`} })(${s.join(", ")})`;
1041
1042
  return await (await e.compileScript(i)).run(t, {
1042
1043
  timeout: r.timeout ?? 500,
1043
1044
  promise: !0,
@@ -1051,12 +1052,12 @@ class A {
1051
1052
  static async evaluateESModule(e, t, n, o, r) {
1052
1053
  let a = n;
1053
1054
  if (o.isCodeBlock) {
1054
- const u = /^\s*(import\s.+?;|export\s.+?;)/gm, h = (n.match(u) || []).join(
1055
+ const h = /^\s*(import\s.+?;|export\s.+?;)/gm, u = (n.match(h) || []).join(
1055
1056
  `
1056
1057
  `
1057
- ), d = n.replace(u, "").trim();
1058
+ ), d = n.replace(h, "").trim();
1058
1059
  a = `
1059
- ${h}
1060
+ ${u}
1060
1061
  const run = function() {
1061
1062
  ${d}
1062
1063
  };
@@ -1076,6 +1077,13 @@ class A {
1076
1077
  release: !0
1077
1078
  });
1078
1079
  }
1080
+ /**
1081
+ * Deep clones a value by serializing and deserializing it to/from JSON,
1082
+ * which strips any isolate-specific object references.
1083
+ */
1084
+ static deepClone(e) {
1085
+ return typeof e > "u" ? e : JSON.parse(JSON.stringify(e));
1086
+ }
1079
1087
  }
1080
1088
  class D {
1081
1089
  /**
@@ -1130,11 +1138,11 @@ class Xe {
1130
1138
  op: "replace",
1131
1139
  path: "/changeset",
1132
1140
  val: s
1133
- }), u = n.getBlue().nodeToSchemaOutput(i, O);
1134
- for (const h of u.changeset ?? []) {
1135
- if (!h.path) continue;
1136
- const d = h.val;
1137
- if ((h.op === "replace" || h.op === "add") && N(d)) {
1141
+ }), h = n.getBlue().nodeToSchemaOutput(i, O);
1142
+ for (const u of h.changeset ?? []) {
1143
+ if (!u.path) continue;
1144
+ const d = u.val;
1145
+ if ((u.op === "replace" || u.op === "add") && N(d)) {
1138
1146
  const p = await this.evaluateChangeValue(
1139
1147
  d,
1140
1148
  n,
@@ -1142,25 +1150,25 @@ class Xe {
1142
1150
  r
1143
1151
  );
1144
1152
  n.addPatch({
1145
- op: h.op,
1146
- path: h.path,
1153
+ op: u.op,
1154
+ path: u.path,
1147
1155
  val: p
1148
1156
  }), n.emitEvent({
1149
1157
  payload: R(
1150
1158
  {
1151
- op: h.op,
1152
- path: n.resolvePath(h.path),
1159
+ op: u.op,
1160
+ path: n.resolvePath(u.path),
1153
1161
  val: a.nodeToJson(p, "original")
1154
1162
  },
1155
1163
  a
1156
1164
  )
1157
1165
  });
1158
1166
  }
1159
- h.op === "remove" && (n.addPatch({ op: h.op, path: h.path }), n.emitEvent({
1167
+ u.op === "remove" && (n.addPatch({ op: u.op, path: u.path }), n.emitEvent({
1160
1168
  payload: R(
1161
1169
  {
1162
- op: h.op,
1163
- path: n.resolvePath(h.path),
1170
+ op: u.op,
1171
+ path: n.resolvePath(u.path),
1164
1172
  val: null
1165
1173
  },
1166
1174
  a
@@ -1244,26 +1252,23 @@ class Ze {
1244
1252
  }
1245
1253
  });
1246
1254
  if (i && typeof i == "object" && "events" in i) {
1247
- const u = i;
1248
- if (Array.isArray(u.events))
1249
- for (const h of u.events)
1255
+ const h = i;
1256
+ if (Array.isArray(h.events))
1257
+ for (const u of h.events)
1250
1258
  n.emitEvent({
1251
- payload: a.jsonValueToNode(Ge(h))
1259
+ payload: a.jsonValueToNode(u)
1252
1260
  });
1253
1261
  }
1254
1262
  return i;
1255
1263
  }
1256
1264
  }
1257
- function Ge(c) {
1258
- return JSON.parse(JSON.stringify(c));
1259
- }
1260
- const et = [
1265
+ const Ge = [
1261
1266
  new Xe(),
1262
1267
  new Ye(),
1263
1268
  new Ze()
1264
1269
  ];
1265
1270
  class re {
1266
- constructor(e = et) {
1271
+ constructor(e = Ge) {
1267
1272
  l(this, "contractType", "Sequential Workflow");
1268
1273
  l(this, "contractBlueId", f["Sequential Workflow"]);
1269
1274
  l(this, "role", "handler");
@@ -1284,26 +1289,26 @@ class re {
1284
1289
  async handle(e, t, n, o) {
1285
1290
  var s;
1286
1291
  const r = {}, a = (s = t.getProperties()) == null ? void 0 : s.steps.getItems();
1287
- for (const [i, u] of (a ?? []).entries()) {
1288
- const h = this.executors.find((p) => p.supports(u));
1289
- if (!h)
1290
- throw new Error(`Unsupported workflow step type "${u.getType()}"`);
1291
- const d = await h.execute(
1292
- u,
1292
+ for (const [i, h] of (a ?? []).entries()) {
1293
+ const u = this.executors.find((p) => p.supports(h));
1294
+ if (!u)
1295
+ throw new Error(`Unsupported workflow step type "${h.getType()}"`);
1296
+ const d = await u.execute(
1297
+ h,
1293
1298
  e,
1294
1299
  n,
1295
1300
  o,
1296
1301
  r
1297
1302
  );
1298
1303
  if (d !== void 0) {
1299
- const p = u.getName(), y = typeof p == "string" ? p : `Step${i + 1}`;
1304
+ const p = h.getName(), y = typeof p == "string" ? p : `Step${i + 1}`;
1300
1305
  r[y] = d;
1301
1306
  }
1302
1307
  await n.flush();
1303
1308
  }
1304
1309
  }
1305
1310
  }
1306
- class tt {
1311
+ class et {
1307
1312
  constructor(e) {
1308
1313
  l(this, "contractType", "Sequential Workflow Operation");
1309
1314
  l(this, "contractBlueId", f["Sequential Workflow Operation"]);
@@ -1330,19 +1335,19 @@ class tt {
1330
1335
  }
1331
1336
  }
1332
1337
  const Q = (c) => E.isTypeOf(c.payload, k);
1333
- class nt extends P {
1338
+ class tt extends P {
1334
1339
  constructor() {
1335
1340
  super(...arguments);
1336
1341
  l(this, "contractType", "Timeline Channel");
1337
1342
  l(this, "contractBlueId", f["Timeline Channel"]);
1338
1343
  }
1339
1344
  supports(t, n, o) {
1340
- var h;
1345
+ var u;
1341
1346
  if (!this.baseSupports(t) || !Q(t)) return !1;
1342
1347
  const a = o.getBlue().nodeToSchemaOutput(
1343
1348
  t.payload,
1344
1349
  k
1345
- ), s = o.getBlue().nodeToSchemaOutput(n, Te), i = (h = a.timeline) == null ? void 0 : h.timelineId;
1350
+ ), s = o.getBlue().nodeToSchemaOutput(n, Te), i = (u = a.timeline) == null ? void 0 : u.timelineId;
1346
1351
  return m(s.timelineId) && m(i) && i === s.timelineId;
1347
1352
  }
1348
1353
  handle(t, n, o, r) {
@@ -1353,12 +1358,12 @@ class nt extends P {
1353
1358
  });
1354
1359
  }
1355
1360
  }
1356
- const ot = [
1361
+ const nt = [
1357
1362
  new Qe(),
1358
1363
  // channels
1359
1364
  new Le(),
1360
1365
  new Fe(),
1361
- new nt(),
1366
+ new tt(),
1362
1367
  new ze(),
1363
1368
  new He(),
1364
1369
  new Ve(),
@@ -1366,17 +1371,17 @@ const ot = [
1366
1371
  new Re(),
1367
1372
  // sequential workflows
1368
1373
  new re(),
1369
- new tt(),
1374
+ new et(),
1370
1375
  // markers
1371
1376
  new Ue()
1372
1377
  ];
1373
- class ut {
1378
+ class lt {
1374
1379
  /**
1375
1380
  * Creates a new document processor
1376
1381
  *
1377
1382
  * @param processors - Initial list of processors to register
1378
1383
  */
1379
- constructor(e, t = ot) {
1384
+ constructor(e, t = nt) {
1380
1385
  l(this, "taskCounter", 0);
1381
1386
  l(this, "eventCounter", 0);
1382
1387
  l(this, "registry");
@@ -1454,11 +1459,11 @@ class ut {
1454
1459
  for (; this.queue.length; ) {
1455
1460
  if (++r > o)
1456
1461
  throw new Error("Possible cycle – too many iterations");
1457
- const s = this.queue.pop(), { nodePath: i, contractName: u, contractNode: h, event: d } = s, p = t.get(i);
1458
- if (!S(p) || !((a = p.getContracts()) != null && a[u]) || !h.getType()) continue;
1459
- const y = this.registry.get(h.getType());
1462
+ const s = this.queue.pop(), { nodePath: i, contractName: h, contractNode: u, event: d } = s, p = t.get(i);
1463
+ if (!S(p) || !((a = p.getContracts()) != null && a[h]) || !u.getType()) continue;
1464
+ const y = this.registry.get(u.getType());
1460
1465
  if (!y) {
1461
- console.warn(`No processor registered for contract: ${u}`);
1466
+ console.warn(`No processor registered for contract: ${h}`);
1462
1467
  continue;
1463
1468
  }
1464
1469
  const w = new G(
@@ -1486,18 +1491,18 @@ class ut {
1486
1491
  try {
1487
1492
  t = L(t, [g.patch]);
1488
1493
  } catch (C) {
1489
- throw We(u, d, C), C;
1494
+ throw We(h, d, C), C;
1490
1495
  }
1491
1496
  } else g.kind === "event" && (n.push(g.event.payload), await this.router.route(t, [], g.event, s.key[5]));
1492
1497
  }
1493
1498
  );
1494
- await y.handle(d, h, w, u), await w.flush();
1499
+ await y.handle(d, u, w, h), await w.flush();
1495
1500
  }
1496
1501
  return { state: t, emitted: n };
1497
1502
  }
1498
1503
  }
1499
1504
  export {
1500
- ut as BlueDocumentProcessor,
1505
+ lt as BlueDocumentProcessor,
1501
1506
  xe as ChannelEventCheckpointProcessor,
1502
1507
  Ve as CompositeTimelineChannelProcessor,
1503
1508
  Fe as DocumentUpdateChannelProcessor,
@@ -1508,7 +1513,7 @@ export {
1508
1513
  ze as MyOSTimelineChannelProcessor,
1509
1514
  Re as OperationProcessor,
1510
1515
  Qe as ProcessEmbeddedProcessor,
1511
- tt as SequentialWorkflowOperationProcessor,
1516
+ et as SequentialWorkflowOperationProcessor,
1512
1517
  re as SequentialWorkflowProcessor,
1513
- nt as TimelineChannelProcessor
1518
+ tt as TimelineChannelProcessor
1514
1519
  };
@@ -55,5 +55,10 @@ export declare class ExpressionEvaluator {
55
55
  * Evaluate code as an ES module with import/export support
56
56
  */
57
57
  private static evaluateESModule;
58
+ /**
59
+ * Deep clones a value by serializing and deserializing it to/from JSON,
60
+ * which strips any isolate-specific object references.
61
+ */
62
+ private static deepClone;
58
63
  }
59
64
  //# sourceMappingURL=ExpressionEvaluator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressionEvaluator.d.ts","sourceRoot":"","sources":["../../../../src/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AASnD;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACrC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAuBD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B;;OAEG;WACU,QAAQ,CAAC,EACpB,IAAI,EACJ,GAAG,EACH,QAAa,EACb,OAAY,GACb,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,iBAAiB,CAAC;QACvB,QAAQ,CAAC,EAAE,UAAU,CAAC;QACtB,OAAO,CAAC,EAAE;YAAE,WAAW,CAAC,EAAE,OAAO,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;KACvD,GAAG,OAAO,CAAC,OAAO,CAAC;IAOpB;;;OAGG;mBACkB,cAAc;IAqCnC;;OAEG;mBACkB,cAAc;IAqDnC;;OAEG;mBACkB,uBAAuB;IAuB5C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAqDnC;;OAEG;mBACkB,oBAAoB;IAwBzC;;OAEG;mBACkB,gBAAgB;CA0CtC"}
1
+ {"version":3,"file":"ExpressionEvaluator.d.ts","sourceRoot":"","sources":["../../../../src/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AASnD;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACrC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAuBD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B;;OAEG;WACU,QAAQ,CAAC,EACpB,IAAI,EACJ,GAAG,EACH,QAAa,EACb,OAAY,GACb,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,iBAAiB,CAAC;QACvB,QAAQ,CAAC,EAAE,UAAU,CAAC;QACtB,OAAO,CAAC,EAAE;YAAE,WAAW,CAAC,EAAE,OAAO,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;KACvD,GAAG,OAAO,CAAC,OAAO,CAAC;IAOpB;;;OAGG;mBACkB,cAAc;IAqCnC;;OAEG;mBACkB,cAAc;IAuDnC;;OAEG;mBACkB,uBAAuB;IAuB5C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAqDnC;;OAEG;mBACkB,oBAAoB;IAwBzC;;OAEG;mBACkB,gBAAgB;IA2CrC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;CAMzB"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@blue-labs/document-processor",
3
- "version": "1.26.1",
3
+ "version": "1.27.0",
4
4
  "dependencies": {
5
- "@blue-labs/language": "1.26.1",
6
- "@blue-labs/shared-utils": "1.26.1",
5
+ "@blue-labs/language": "1.27.0",
6
+ "@blue-labs/shared-utils": "1.27.0",
7
7
  "isolated-vm": "^5.0.4"
8
8
  },
9
9
  "main": "./dist/index.js",