@blue-labs/document-processor 1.33.1 → 1.33.3
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,9 +1,9 @@
|
|
|
1
|
-
"use strict";var ve=Object.defineProperty;var we=(a,e,t)=>e in a?ve(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var l=(a,e,t)=>we(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@blue-repository/core-dev"),m=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),C=require("@blue-repository/myos-dev"),S=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class G{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=S(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:S(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return S(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class V extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class _ extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class K extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class Y extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(a){return v.deepFreeze(a)}function M(a){return a.clone()}function D(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,h.ProcessEmbeddedSchema)){const d=e.nodeToSchemaOutput(s,h.ProcessEmbeddedSchema).paths??[];for(const u of d)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))D(s,e,S(t,r),n);return n}function U(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function z(a,e){if(!e.length)return a;let t=M(a);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new V(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class 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 r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Te=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Pe=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Se{constructor(){l(this,"queue");this.queue=new be([],Pe)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Ce{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}const O=class O{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=O.MAX_TRACE_LENGTH?o.slice(o.length-(O.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}};l(O,"MAX_TRACE_LENGTH",128);let j=O;function Ne(a){return Object.entries(a.getContracts()??{})}const Ie=64;class ke{constructor(e,t,n,o,r){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new j}async route(e,t,n,o,r=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const d=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,d,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const d=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,d,n,o,r)}}const s=S("/",t.join("/")),i=e.get(s);N(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[d,u]of Ne(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${d}`);continue}const f={nodePath:o,contractName:d,contractNode:u,event:r},g=new G(()=>t,f,this.blue);if(p.supports(r,u,g,d))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:d,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:d,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var T;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:d}=e;if(d>=Ie)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((T=r.getTaskInfo())==null?void 0:T.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(b=>b.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(b=>b.kind==="event");for(const b of g)await this.route(i,[],b.event,c,d+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const d=this.registry.orderOf(c),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+i,g=r.seq;if(g===void 0)throw new Error("Event sequence missing");const T=Te(s,g,d,p,n,f);{const y=`${o}#${n}`,A=r.trace??[];if(r.source!=="external"&&A.includes(y))throw new Error(`Loop detected: repeated hop ${y} within the same event chain`)}const b=this.traceManager.addHop(r,o,n);this.queue.push({key:T,nodePath:o,contractName:n,contractNode:t,event:b})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Be=(a,e,t)=>{(t instanceof V||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function R(a,e){const t=M(a),n=o=>{if(!N(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!m.BlueNodeTypeSchema.isTypeOf(r.checkpoint,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 D(t,e)){const r=t.get(o);N(r)&&n(r)}return B(t)}function Oe(a,e){const t=M(a);return N(t)&&(Z(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:h.blueIds["Initialized Marker"]}}))),B(t)}function Z(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,h.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ee{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 getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof m.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var s;if(!e.channelName||!((s=e.rootEvent)!=null&&s.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const H=(a,e)=>a.get(e)!==void 0;class Me{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const s=S(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;H(e,s)?t.push({op:H(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class te{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",h.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class I{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class ne extends I{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",h.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.DocumentUpdateChannelSchema),s=t.payload.get("/path");if(!s)return!1;const i=r.path;return v.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class oe extends I{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",h.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema);return w(t.originNodePath)&&w(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const s=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;w(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class re{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",h.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class se extends I{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",h.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||t.emissionType!=="lifecycle"||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel",emissionType:t.emissionType})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,h.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var s;const r=(s=n.getProperties())==null?void 0:s.event;if(!r)return!0;try{const i=o.getBlue(),c=i.resolve(t.payload);return i.isTypeOfNode(c,r)}catch(i){return console.warn("Error during lifecycle event pattern matching:",i),!1}}}const F=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,h.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ae extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",C.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!F(t,o))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,C.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,C.MyOSTimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){F(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ie extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",C.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:s}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,s)&&this.isEventPatternMatch(r,s,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),s=r.nodeToSchemaOutput(t.payload,C.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,C.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var s;const o=t.agentId,r=(s=n.agent)==null?void 0:s.agentId;return w(o)&&w(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const s=t.event;if(!s)return!1;try{const i=o.getBlue(),c=i.nodeToJson(s),d=i.nodeToJson(r);return v.deepContains(c,d)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class ce{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",h.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,h.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),d=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&d&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,h.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,h.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,h.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return w(e==null?void 0:e.operation)&&(e==null?void 0:e.operation)===t}isOperationChannelMatch(e,t){const n=t.channel;return v.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(v.isNullable(o))return!0;const r=n.getBlue(),s=e==null?void 0:e.request;if(v.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class le{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",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)})}}let E=null;function qe(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class ${static getIvmUnavailableMessage(){const e=typeof process<"u"&&process.version?process.version:"unknown",t=typeof process<"u"&&process.platform?process.platform:"unknown",n=typeof process<"u"&&process.arch?process.arch:"unknown";return["isolated-vm is required for expression evaluation but could not be loaded.","This feature only works in a Node.js environment with the native addon available.","",`Detected environment: Node ${e} on ${t}/${n}.`,"","Common causes:","- Running in a non-Node environment (browser, edge/runtime without Node).","- 'isolated-vm' is not installed, or failed to build its native addon.","- The module was bundled/stripped by a build tool.","","How to fix:","- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.","- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).","- Run this code on a supported Node.js runtime (not browser/edge workers)."].join(`
|
|
2
|
-
`)}static async
|
|
1
|
+
"use strict";var be=Object.create;var j=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var Ne=(a,e,t)=>e in a?j(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Ie=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!Ce.call(a,o)&&o!==t&&j(a,o,{get:()=>e[o],enumerable:!(n=Te(e,o))||n.enumerable});return a};var z=(a,e,t)=>(t=a!=null?be(Se(a)):{},Ie(e||!a||!a.__esModule?j(t,"default",{value:a,enumerable:!0}):t,a));var l=(a,e,t)=>Ne(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@blue-repository/core-dev"),m=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),C=require("@blue-repository/myos-dev"),S=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class Y{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=S(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:S(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return S(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class _ extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class W 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 Z extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class ee extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(a){return v.deepFreeze(a)}function M(a){return a.clone()}function D(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,h.ProcessEmbeddedSchema)){const d=e.nodeToSchemaOutput(s,h.ProcessEmbeddedSchema).paths??[];for(const u of d)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))D(s,e,S(t,r),n);return n}function R(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function H(a,e){if(!e.length)return a;let t=M(a);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new _(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class ke{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Be=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Oe=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Me{constructor(){l(this,"queue");this.queue=new ke([],Oe)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class qe{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}const O=class O{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=O.MAX_TRACE_LENGTH?o.slice(o.length-(O.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}};l(O,"MAX_TRACE_LENGTH",128);let x=O;function $e(a){return Object.entries(a.getContracts()??{})}const De=64;class Ae{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 x}async route(e,t,n,o,r=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const d=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,d,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const d=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,d,n,o,r)}}const s=S("/",t.join("/")),i=e.get(s);N(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[d,u]of $e(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${d}`);continue}const f={nodePath:o,contractName:d,contractNode:u,event:r},g=new Y(()=>t,f,this.blue);if(p.supports(r,u,g,d))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:d,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:d,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var T;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:d}=e;if(d>=De)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((T=r.getTaskInfo())==null?void 0:T.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(b=>b.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(b=>b.kind==="event");for(const b of g)await this.route(i,[],b.event,c,d+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const d=this.registry.orderOf(c),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+i,g=r.seq;if(g===void 0)throw new Error("Event sequence missing");const T=Be(s,g,d,p,n,f);{const E=`${o}#${n}`,A=r.trace??[];if(r.source!=="external"&&A.includes(E))throw new Error(`Loop detected: repeated hop ${E} within the same event chain`)}const b=this.traceManager.addHop(r,o,n);this.queue.push({key:T,nodePath:o,contractName:n,contractNode:t,event:b})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const je=(a,e,t)=>{(t instanceof _||t instanceof W)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function F(a,e){const t=M(a),n=o=>{if(!N(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!m.BlueNodeTypeSchema.isTypeOf(r.checkpoint,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 D(t,e)){const r=t.get(o);N(r)&&n(r)}return B(t)}function xe(a,e){const t=M(a);return N(t)&&(te(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:h.blueIds["Initialized Marker"]}}))),B(t)}function te(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,h.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ne{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 getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof m.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var s;if(!e.channelName||!((s=e.rootEvent)!=null&&s.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const X=(a,e)=>a.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 s=S(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;X(e,s)?t.push({op:X(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class oe{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",h.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class I{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class re extends I{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",h.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.DocumentUpdateChannelSchema),s=t.payload.get("/path");if(!s)return!1;const i=r.path;return v.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class se extends I{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 w(t.originNodePath)&&w(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const s=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;w(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class ae{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",h.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ie extends I{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",h.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||t.emissionType!=="lifecycle"||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel",emissionType:t.emissionType})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,h.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var s;const r=(s=n.getProperties())==null?void 0:s.event;if(!r)return!0;try{const i=o.getBlue(),c=i.resolve(t.payload);return i.isTypeOfNode(c,r)}catch(i){return console.warn("Error during lifecycle event pattern matching:",i),!1}}}const Q=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,h.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ce extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",C.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t,o))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,C.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,C.MyOSTimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){Q(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class le extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",C.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:s}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,s)&&this.isEventPatternMatch(r,s,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),s=r.nodeToSchemaOutput(t.payload,C.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,C.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var s;const o=t.agentId,r=(s=n.agent)==null?void 0:s.agentId;return w(o)&&w(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const s=t.event;if(!s)return!1;try{const i=o.getBlue(),c=i.nodeToJson(s),d=i.nodeToJson(r);return v.deepContains(c,d)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class ue{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",h.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,h.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),d=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&d&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,h.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,h.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,h.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return w(e==null?void 0:e.operation)&&(e==null?void 0:e.operation)===t}isOperationChannelMatch(e,t){const n=t.channel;return v.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(v.isNullable(o))return!0;const r=n.getBlue(),s=e==null?void 0:e.request;if(v.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class de{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)})}}const _e=!process.env.SKIP_ISOLATED_VM;let y=null;if(_e)try{y=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function We(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class ${static getIvmUnavailableMessage(){const e=typeof process<"u"&&process.version?process.version:"unknown",t=typeof process<"u"&&process.platform?process.platform:"unknown",n=typeof process<"u"&&process.arch?process.arch:"unknown";return["isolated-vm is required for expression evaluation but could not be loaded.","This feature only works in a Node.js environment with the native addon available.","",`Detected environment: Node ${e} on ${t}/${n}.`,"","Common causes:","- Running in a non-Node environment (browser, edge/runtime without Node).","- 'isolated-vm' is not installed, or failed to build its native addon.","- The module was bundled/stripped by a build tool.","","How to fix:","- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.","- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).","- Run this code on a supported Node.js runtime (not browser/edge workers)."].join(`
|
|
2
|
+
`)}static async ensureIvm(){if(y)return y;try{typeof require=="function"?y=require("isolated-vm"):y=(await import("isolated-vm")).default??await import("isolated-vm")}catch(e){console.error(e),y=null}return y}static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(await this.ensureIvm(),!y)throw new Error(this.getIvmUnavailableMessage());return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!y)throw new Error(this.getIvmUnavailableMessage());const r=new y.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,d=this.createModuleResolver(r,s,c,n);let u;return We(e)?u=await this.evaluateESModule(r,s,e,o,d):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new ee(e,c):new Z(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!y)throw new Error("isolated-vm not available");const n=new y.Callback((...r)=>console.log(...r)),o=new y.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,s]of Object.entries(t))typeof s=="function"?await e.set(r,new y.Callback(s)):await e.set(r,new y.ExternalCopy(s).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const s=r.slice(5),i=o.loadBlueContent;if(typeof i!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const c=await i(s),d=await e.compileModule(c);return n.set(r,d),await d.instantiate(t,this.createModuleResolver(e,t,n,o)),d}if(/^https?:\/\//.test(r)){let s;if(typeof o.loadExternalModule=="function")s=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const i=await e.compileModule(s);return n.set(r,i),await i.instantiate(t,this.createModuleResolver(e,t,n,o)),i}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const s=Object.keys(o).join(", "),i=Object.keys(o).map(u=>u),c=`(async (${s}) => { ${r.isCodeBlock?n:`return (${n});`} })(${i.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let s=n;if(o.isCodeBlock){const d=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(d)||[]).join(`
|
|
3
3
|
`),p=n.replace(d,"").trim();s=`
|
|
4
4
|
${u}
|
|
5
5
|
const run = function() {
|
|
6
6
|
${p}
|
|
7
7
|
};
|
|
8
8
|
export default run();
|
|
9
|
-
`}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class W{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=m.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return m.isBigNumber(c)?c.toNumber():N(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const $e=/^\$\{([\s\S]*)\}$/,De=/\$\{([\s\S]*?)\}/,P=a=>typeof a!="string"?!1:$e.test(a),x=a=>typeof a!="string"?!1:De.test(a),ue=a=>{if(!P(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return W.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(P(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(x(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await $.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function X(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function Ae(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class je{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),d=n.getBlue().nodeToSchemaOutput(c,h.UpdateDocumentSchema);for(const u of d.changeset??[]){if(!u.path)continue;const p=await this.evaluateChangePath(u.path,n,t,r),f=u.val;if((u.op==="replace"||u.op==="add")&&v.isNonNullable(f)){const g=await this.evaluateChangeValue(f,n,t,r);n.addPatch({op:u.op,path:p,val:g}),n.emitEvent({payload:X({op:u.op,path:n.resolvePath(p),val:s.nodeToJson(g,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:p}),n.emitEvent({payload:X({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(P(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:W.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}if(N(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),s=t.getBlue();if(P(r)||typeof r=="string"&&x(r)){const i=q.createBindings(t,n,o),c=await q.evaluate(String(r),t,i,{coerceToString:!P(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=q.createBindings(t,n,o);if(P(e)||x(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class xe{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,h.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class Ve{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,h.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await $.evaluate({code:i.code,ctx:n,bindings:W.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const d=c;if(Array.isArray(d.events))for(const u of d.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const _e=[new je,new xe,new Ve];class J{constructor(e=_e){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",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 r=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){var i;const r={},s=(i=t.getProperties())==null?void 0:i.steps.getItems();for(const[c,d]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(d));if(!u)throw new Error(`Unsupported workflow step type "${d.getType()}"`);const p=await u.execute(d,e,n,o,r);if(p!==void 0){const f=d.getName(),g=typeof f=="string"?f:`Step${c+1}`;r[g]=p}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return v.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){var r;const o=(r=t.getProperties())==null?void 0:r.event;if(!o)return!0;try{const s=n.getBlue(),i=s.resolve(e.payload);return s.isTypeOfNode(i,o)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class de{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 J}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&v.isNonNullable(i)&&v.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const Q=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,h.TimelineEntrySchema);class he extends I{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",h.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,h.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,h.TimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class pe extends I{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",h.blueIds["Triggered Event Channel"])}supports(t){return this.baseSupports(t)?t.emissionType==="triggered":!1}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const We=[new le,new oe,new ne,new he,new ae,new ie,new te,new se,new pe,new ce,new J,new de,new re];class Je{constructor(e,t=We){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Me);this.blue=e,this.registry=new Ce(t),this.queue=new Se,this.router=new ke(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ee(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=R(B(e),this.blue);const n={payload:Ae(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=Oe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=R(B(e),this.blue);const o=[];if(!Z(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=z(n,c))}finally{this.checkpointCache.clear()}return{state:M(n),emitted:o}}async drainQueue(e){var s;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const i=this.queue.pop(),{nodePath:c,contractName:d,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[d])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${d}`);continue}const T=new G(()=>t,i,this.blue,async b=>{for(const y of b)if(y.kind==="patch"){const A=D(t,this.blue);for(const k of A){const fe=y.patch.op==="move"||y.patch.op==="copy"?[y.patch.from,y.patch.path]:[y.patch.path],L=T.getNodePath(),ge=fe.some(Ee=>U(Ee,k.absPath)),ye=U(L,k.absPath);if(ge&&!ye)throw new _(y.patch,k.absPath,L)}try{t=z(t,[y.patch])}catch(k){throw Be(d,p,k),k}}else y.kind==="event"&&(n.push(y.event.payload),await this.router.route(t,[],y.event,i.key[5]))});await g.handle(p,u,T,d),await T.flush()}return{state:t,emitted:n}}}class me{process(e,t){const n=t.getValue();if(P(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(P(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Le=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:me},Symbol.toStringTag,{value:"Module"}));function Ue(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new me,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Je;exports.ChannelEventCheckpointProcessor=ee;exports.CodeBlockEvaluationError=Y;exports.CompositeTimelineChannelProcessor=te;exports.DocumentUpdateChannelProcessor=ne;exports.EmbeddedDocumentModificationError=_;exports.EmbeddedNodeChannelProcessor=oe;exports.ExpressionEvaluationError=K;exports.InitializedMarkerProcessor=re;exports.LifecycleEventChannelProcessor=se;exports.MergingProcessors=Le;exports.MyOSAgentChannelProcessor=ie;exports.MyOSTimelineChannelProcessor=ae;exports.OperationProcessor=ce;exports.PatchApplicationError=V;exports.ProcessEmbeddedProcessor=le;exports.SequentialWorkflowOperationProcessor=de;exports.SequentialWorkflowProcessor=J;exports.TimelineChannelProcessor=he;exports.TriggeredEventChannelProcessor=pe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ue;
|
|
9
|
+
`}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class J{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=m.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return m.isBigNumber(c)?c.toNumber():N(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const Je=/^\$\{([\s\S]*)\}$/,Ue=/\$\{([\s\S]*?)\}/,P=a=>typeof a!="string"?!1:Je.test(a),V=a=>typeof a!="string"?!1:Ue.test(a),he=a=>{if(!P(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return J.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(P(e)){const s=he(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(V(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await $.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function G(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function Le(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class ze{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),d=n.getBlue().nodeToSchemaOutput(c,h.UpdateDocumentSchema);for(const u of d.changeset??[]){if(!u.path)continue;const p=await this.evaluateChangePath(u.path,n,t,r),f=u.val;if((u.op==="replace"||u.op==="add")&&v.isNonNullable(f)){const g=await this.evaluateChangeValue(f,n,t,r);n.addPatch({op:u.op,path:p,val:g}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:s.nodeToJson(g,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:p}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(P(e)){const s=he(e),i=await $.evaluate({code:s,ctx:t,bindings:J.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}if(N(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),s=t.getBlue();if(P(r)||typeof r=="string"&&V(r)){const i=q.createBindings(t,n,o),c=await q.evaluate(String(r),t,i,{coerceToString:!P(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=q.createBindings(t,n,o);if(P(e)||V(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class Re{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,h.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class He{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,h.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await $.evaluate({code:i.code,ctx:n,bindings:J.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const d=c;if(Array.isArray(d.events))for(const u of d.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const Fe=[new ze,new Re,new He];class U{constructor(e=Fe){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 r=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){var i;const r={},s=(i=t.getProperties())==null?void 0:i.steps.getItems();for(const[c,d]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(d));if(!u)throw new Error(`Unsupported workflow step type "${d.getType()}"`);const p=await u.execute(d,e,n,o,r);if(p!==void 0){const f=d.getName(),g=typeof f=="string"?f:`Step${c+1}`;r[g]=p}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return v.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){var r;const o=(r=t.getProperties())==null?void 0:r.event;if(!o)return!0;try{const s=n.getBlue(),i=s.resolve(e.payload);return s.isTypeOfNode(i,o)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class pe{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 U}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&v.isNonNullable(i)&&v.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const K=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,h.TimelineEntrySchema);class me extends I{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",h.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!K(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,h.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,h.TimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){K(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class fe extends I{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",h.blueIds["Triggered Event Channel"])}supports(t){return this.baseSupports(t)?t.emissionType==="triggered":!1}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const Xe=[new de,new se,new re,new me,new ce,new le,new oe,new ie,new fe,new ue,new U,new pe,new ae];class Qe{constructor(e,t=Xe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Ve);this.blue=e,this.registry=new qe(t),this.queue=new Me,this.router=new Ae(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ne(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=F(B(e),this.blue);const n={payload:Le(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=xe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=F(B(e),this.blue);const o=[];if(!te(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=H(n,c))}finally{this.checkpointCache.clear()}return{state:M(n),emitted:o}}async drainQueue(e){var s;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const i=this.queue.pop(),{nodePath:c,contractName:d,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[d])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${d}`);continue}const T=new Y(()=>t,i,this.blue,async b=>{for(const E of b)if(E.kind==="patch"){const A=D(t,this.blue);for(const k of A){const ye=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],L=T.getNodePath(),Ee=ye.some(we=>R(we,k.absPath)),ve=R(L,k.absPath);if(Ee&&!ve)throw new W(E.patch,k.absPath,L)}try{t=H(t,[E.patch])}catch(k){throw je(d,p,k),k}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,i.key[5]))});await g.handle(p,u,T,d),await T.flush()}return{state:t,emitted:n}}}class ge{process(e,t){const n=t.getValue();if(P(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(P(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Ge=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ge},Symbol.toStringTag,{value:"Module"}));function Ke(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new ge,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Qe;exports.ChannelEventCheckpointProcessor=ne;exports.CodeBlockEvaluationError=ee;exports.CompositeTimelineChannelProcessor=oe;exports.DocumentUpdateChannelProcessor=re;exports.EmbeddedDocumentModificationError=W;exports.EmbeddedNodeChannelProcessor=se;exports.ExpressionEvaluationError=Z;exports.InitializedMarkerProcessor=ae;exports.LifecycleEventChannelProcessor=ie;exports.MergingProcessors=Ge;exports.MyOSAgentChannelProcessor=le;exports.MyOSTimelineChannelProcessor=ce;exports.OperationProcessor=ue;exports.PatchApplicationError=_;exports.ProcessEmbeddedProcessor=de;exports.SequentialWorkflowOperationProcessor=pe;exports.SequentialWorkflowProcessor=U;exports.TimelineChannelProcessor=me;exports.TriggeredEventChannelProcessor=fe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ke;
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
var ge = (a, e, t) => e in a ?
|
|
1
|
+
var me = Object.defineProperty;
|
|
2
|
+
var ge = (a, e, t) => e in a ? me(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
|
|
3
3
|
var l = (a, e, t) => ge(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
-
import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as ye, blueIds as
|
|
5
|
-
import { applyBlueNodePatch as te, BlueNode as ke, isBigNumber as
|
|
4
|
+
import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as ye, blueIds as y, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as we, DocumentUpdateChannelSchema as ve, EmbeddedNodeChannelSchema as F, LifecycleEventSchema as Te, TimelineEntrySchema as O, OperationSchema as be, OperationRequestSchema as Pe, UpdateDocumentSchema as j, TriggerEventSchema as x, JavaScriptCodeSchema as V, SequentialWorkflowSchema as Se, SequentialWorkflowOperationSchema as Ce, TimelineChannelSchema as Ne } from "@blue-repository/core-dev";
|
|
5
|
+
import { applyBlueNodePatch as te, BlueNode as ke, isBigNumber as J, BlueNodeTypeSchema as P, ResolvedBlueNode as Ie, MergingProcessors as k } from "@blue-labs/language";
|
|
6
6
|
import { deepFreeze as Be, isNonNullable as M, deepContains as Oe, isNullable as _ } from "@blue-labs/shared-utils";
|
|
7
7
|
import { blueIds as ne, MyOSTimelineEntrySchema as oe, MyOSTimelineChannelSchema as Me, MyOSAgentEventSchema as $e, MyOSAgentChannelSchema as qe } from "@blue-repository/myos-dev";
|
|
8
8
|
const b = (...a) => a.map((e, t) => {
|
|
@@ -101,11 +101,11 @@ function z(a, e, t = "/", n = []) {
|
|
|
101
101
|
const o = a.getContracts() ?? {};
|
|
102
102
|
for (const [r, s] of Object.entries(o))
|
|
103
103
|
if (e.isTypeOf(s, W)) {
|
|
104
|
-
const
|
|
104
|
+
const h = e.nodeToSchemaOutput(
|
|
105
105
|
s,
|
|
106
106
|
W
|
|
107
107
|
).paths ?? [];
|
|
108
|
-
for (const u of
|
|
108
|
+
for (const u of h)
|
|
109
109
|
n.push({
|
|
110
110
|
absPath: b(t, u),
|
|
111
111
|
contractPath: b(t, `contracts/${r}`)
|
|
@@ -345,11 +345,11 @@ const B = class B {
|
|
|
345
345
|
}
|
|
346
346
|
};
|
|
347
347
|
l(B, "MAX_TRACE_LENGTH", 128);
|
|
348
|
-
let
|
|
349
|
-
function
|
|
348
|
+
let L = B;
|
|
349
|
+
function Je(a) {
|
|
350
350
|
return Object.entries(a.getContracts() ?? {});
|
|
351
351
|
}
|
|
352
|
-
const
|
|
352
|
+
const Le = 64;
|
|
353
353
|
class Ue {
|
|
354
354
|
/**
|
|
355
355
|
* Creates a new event router
|
|
@@ -361,7 +361,7 @@ class Ue {
|
|
|
361
361
|
*/
|
|
362
362
|
constructor(e, t, n, o, r) {
|
|
363
363
|
l(this, "traceManager");
|
|
364
|
-
this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new
|
|
364
|
+
this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new L();
|
|
365
365
|
}
|
|
366
366
|
/**
|
|
367
367
|
* Routes an event to matching contracts in the document
|
|
@@ -376,12 +376,12 @@ class Ue {
|
|
|
376
376
|
var c;
|
|
377
377
|
if (n.seq === void 0 && (n.seq = this.getNextEventSeq()), t.length === 0) {
|
|
378
378
|
if (n.dispatchPath) {
|
|
379
|
-
const
|
|
380
|
-
return delete u.dispatchPath, this.route(e,
|
|
379
|
+
const h = n.dispatchPath.split("/").filter(Boolean), u = { ...n };
|
|
380
|
+
return delete u.dispatchPath, this.route(e, h, u, o, r);
|
|
381
381
|
}
|
|
382
382
|
if (n.source === "channel" && n.originNodePath && n.originNodePath !== "/") {
|
|
383
|
-
const
|
|
384
|
-
return this.route(e,
|
|
383
|
+
const h = ((c = n.originNodePath) == null ? void 0 : c.split("/").filter(Boolean)) ?? [];
|
|
384
|
+
return this.route(e, h, n, o, r);
|
|
385
385
|
}
|
|
386
386
|
}
|
|
387
387
|
const s = b("/", t.join("/")), i = e.get(s);
|
|
@@ -409,28 +409,28 @@ class Ue {
|
|
|
409
409
|
inlineDepth: c
|
|
410
410
|
} = e;
|
|
411
411
|
if (!this.shouldSkipForChannel(r, o))
|
|
412
|
-
for (const [
|
|
412
|
+
for (const [h, u] of Je(n)) {
|
|
413
413
|
if (!u.getType()) continue;
|
|
414
|
-
const
|
|
415
|
-
if (!
|
|
416
|
-
console.warn(`No processor registered for contract: ${
|
|
414
|
+
const d = this.registry.get(u.getType());
|
|
415
|
+
if (!d) {
|
|
416
|
+
console.warn(`No processor registered for contract: ${h}`);
|
|
417
417
|
continue;
|
|
418
418
|
}
|
|
419
419
|
const p = {
|
|
420
420
|
nodePath: o,
|
|
421
|
-
contractName:
|
|
421
|
+
contractName: h,
|
|
422
422
|
contractNode: u,
|
|
423
423
|
event: r
|
|
424
|
-
},
|
|
425
|
-
if (
|
|
426
|
-
switch (
|
|
424
|
+
}, f = new re(() => t, p, this.blue);
|
|
425
|
+
if (d.supports(r, u, f, h))
|
|
426
|
+
switch (d.role) {
|
|
427
427
|
case "adapter":
|
|
428
428
|
await this.processAdapter({
|
|
429
|
-
cp:
|
|
429
|
+
cp: d,
|
|
430
430
|
event: r,
|
|
431
431
|
contractNode: u,
|
|
432
|
-
ctx:
|
|
433
|
-
contractName:
|
|
432
|
+
ctx: f,
|
|
433
|
+
contractName: h,
|
|
434
434
|
doc: t,
|
|
435
435
|
afterTaskId: s,
|
|
436
436
|
inlineDepth: c
|
|
@@ -439,7 +439,7 @@ class Ue {
|
|
|
439
439
|
case "handler":
|
|
440
440
|
this.scheduleHandler({
|
|
441
441
|
contractNode: u,
|
|
442
|
-
contractName:
|
|
442
|
+
contractName: h,
|
|
443
443
|
nodePath: o,
|
|
444
444
|
event: r,
|
|
445
445
|
depth: i.length,
|
|
@@ -453,7 +453,7 @@ class Ue {
|
|
|
453
453
|
* Processes an adapter contract and routes any emitted events
|
|
454
454
|
*/
|
|
455
455
|
async processAdapter(e) {
|
|
456
|
-
var
|
|
456
|
+
var v;
|
|
457
457
|
const {
|
|
458
458
|
cp: t,
|
|
459
459
|
event: n,
|
|
@@ -462,24 +462,24 @@ class Ue {
|
|
|
462
462
|
contractName: s,
|
|
463
463
|
doc: i,
|
|
464
464
|
afterTaskId: c,
|
|
465
|
-
inlineDepth:
|
|
465
|
+
inlineDepth: h
|
|
466
466
|
} = e;
|
|
467
|
-
if (
|
|
467
|
+
if (h >= Le)
|
|
468
468
|
throw new Error("Adapter recursion limit reached");
|
|
469
469
|
const u = this.traceManager.addHop(
|
|
470
470
|
n,
|
|
471
|
-
((
|
|
471
|
+
((v = r.getTaskInfo()) == null ? void 0 : v.nodePath) ?? "",
|
|
472
472
|
s
|
|
473
473
|
);
|
|
474
474
|
await t.handle(u, o, r, s);
|
|
475
|
-
const
|
|
476
|
-
if (
|
|
475
|
+
const d = await r.flush();
|
|
476
|
+
if (d.find((w) => w.kind === "patch"))
|
|
477
477
|
throw new Error(
|
|
478
478
|
`Contract "${s}" (adapter) attempted to patch the document`
|
|
479
479
|
);
|
|
480
|
-
const
|
|
481
|
-
for (const
|
|
482
|
-
await this.route(i, [],
|
|
480
|
+
const f = d.filter((w) => w.kind === "event");
|
|
481
|
+
for (const w of f)
|
|
482
|
+
await this.route(i, [], w.event, c, h + 1);
|
|
483
483
|
}
|
|
484
484
|
/**
|
|
485
485
|
* Schedules a handler contract for future execution
|
|
@@ -490,31 +490,31 @@ class Ue {
|
|
|
490
490
|
console.warn(`Contract node type is not defined for: ${n}`);
|
|
491
491
|
return;
|
|
492
492
|
}
|
|
493
|
-
const
|
|
494
|
-
if (
|
|
493
|
+
const h = this.registry.orderOf(c), u = t.get("/order"), d = J(u) ? u.toNumber() : 0, p = this.getNextTaskId() + i, f = r.seq;
|
|
494
|
+
if (f === void 0)
|
|
495
495
|
throw new Error("Event sequence missing");
|
|
496
|
-
const
|
|
496
|
+
const v = xe(
|
|
497
497
|
s,
|
|
498
|
-
|
|
499
|
-
d,
|
|
498
|
+
f,
|
|
500
499
|
h,
|
|
500
|
+
d,
|
|
501
501
|
n,
|
|
502
502
|
p
|
|
503
503
|
);
|
|
504
504
|
{
|
|
505
|
-
const
|
|
506
|
-
if (r.source !== "external" && D.includes(
|
|
505
|
+
const g = `${o}#${n}`, D = r.trace ?? [];
|
|
506
|
+
if (r.source !== "external" && D.includes(g))
|
|
507
507
|
throw new Error(
|
|
508
|
-
`Loop detected: repeated hop ${
|
|
508
|
+
`Loop detected: repeated hop ${g} within the same event chain`
|
|
509
509
|
);
|
|
510
510
|
}
|
|
511
|
-
const
|
|
511
|
+
const w = this.traceManager.addHop(r, o, n);
|
|
512
512
|
this.queue.push({
|
|
513
|
-
key:
|
|
513
|
+
key: v,
|
|
514
514
|
nodePath: o,
|
|
515
515
|
contractName: n,
|
|
516
516
|
contractNode: t,
|
|
517
|
-
event:
|
|
517
|
+
event: w
|
|
518
518
|
});
|
|
519
519
|
}
|
|
520
520
|
/**
|
|
@@ -542,7 +542,7 @@ function G(a, e) {
|
|
|
542
542
|
e.jsonValueToNode({
|
|
543
543
|
type: {
|
|
544
544
|
name: "Channel Event Checkpoint",
|
|
545
|
-
blueId:
|
|
545
|
+
blueId: y["Channel Event Checkpoint"]
|
|
546
546
|
},
|
|
547
547
|
lastEvents: {}
|
|
548
548
|
})
|
|
@@ -562,7 +562,7 @@ function Re(a, e) {
|
|
|
562
562
|
e.jsonValueToNode({
|
|
563
563
|
type: {
|
|
564
564
|
name: "Initialized Marker",
|
|
565
|
-
blueId:
|
|
565
|
+
blueId: y["Initialized Marker"]
|
|
566
566
|
}
|
|
567
567
|
})
|
|
568
568
|
)), I(t);
|
|
@@ -578,7 +578,7 @@ function ie(a, e) {
|
|
|
578
578
|
class He {
|
|
579
579
|
constructor(e) {
|
|
580
580
|
l(this, "contractType", "Channel Event Checkpoint");
|
|
581
|
-
l(this, "contractBlueId",
|
|
581
|
+
l(this, "contractBlueId", y["Channel Event Checkpoint"]);
|
|
582
582
|
l(this, "role", "handler");
|
|
583
583
|
this.cache = e;
|
|
584
584
|
}
|
|
@@ -644,11 +644,11 @@ class Fe {
|
|
|
644
644
|
class Xe {
|
|
645
645
|
constructor() {
|
|
646
646
|
l(this, "contractType", "Composite Timeline Channel");
|
|
647
|
-
l(this, "contractBlueId",
|
|
647
|
+
l(this, "contractBlueId", y["Composite Timeline Channel"]);
|
|
648
648
|
l(this, "role", "adapter");
|
|
649
649
|
}
|
|
650
650
|
supports(e, t, n) {
|
|
651
|
-
const o = n.getBlue().nodeToSchemaOutput(t,
|
|
651
|
+
const o = n.getBlue().nodeToSchemaOutput(t, we);
|
|
652
652
|
return !o.channels || !e.channelName ? !1 : o.channels.includes(e.channelName);
|
|
653
653
|
}
|
|
654
654
|
handle(e, t, n, o) {
|
|
@@ -675,11 +675,11 @@ class Qe extends C {
|
|
|
675
675
|
constructor() {
|
|
676
676
|
super(...arguments);
|
|
677
677
|
l(this, "contractType", "Document Update Channel");
|
|
678
|
-
l(this, "contractBlueId",
|
|
678
|
+
l(this, "contractBlueId", y["Document Update Channel"]);
|
|
679
679
|
}
|
|
680
680
|
supports(t, n, o) {
|
|
681
681
|
if (!this.baseSupports(t) || t.emissionType !== "update") return !1;
|
|
682
|
-
const r = o.getBlue().nodeToSchemaOutput(n,
|
|
682
|
+
const r = o.getBlue().nodeToSchemaOutput(n, ve), s = t.payload.get("/path");
|
|
683
683
|
if (!s) return !1;
|
|
684
684
|
const i = r.path;
|
|
685
685
|
return M(i) && s === o.resolvePath(i);
|
|
@@ -696,7 +696,7 @@ class Ge extends C {
|
|
|
696
696
|
constructor() {
|
|
697
697
|
super(...arguments);
|
|
698
698
|
l(this, "contractType", "Embedded Node Channel");
|
|
699
|
-
l(this, "contractBlueId",
|
|
699
|
+
l(this, "contractBlueId", y["Embedded Node Channel"]);
|
|
700
700
|
}
|
|
701
701
|
supports(t, n, o) {
|
|
702
702
|
if (!this.baseSupports(t)) return !1;
|
|
@@ -715,7 +715,7 @@ class Ge extends C {
|
|
|
715
715
|
class Ke {
|
|
716
716
|
constructor() {
|
|
717
717
|
l(this, "contractType", "Initialized Marker");
|
|
718
|
-
l(this, "contractBlueId",
|
|
718
|
+
l(this, "contractBlueId", y["Initialized Marker"]);
|
|
719
719
|
l(this, "role", "marker");
|
|
720
720
|
}
|
|
721
721
|
supports() {
|
|
@@ -728,7 +728,7 @@ class Ye extends C {
|
|
|
728
728
|
constructor() {
|
|
729
729
|
super(...arguments);
|
|
730
730
|
l(this, "contractType", "Lifecycle Event Channel");
|
|
731
|
-
l(this, "contractBlueId",
|
|
731
|
+
l(this, "contractBlueId", y["Lifecycle Event Channel"]);
|
|
732
732
|
}
|
|
733
733
|
supports(t, n, o) {
|
|
734
734
|
return !this.baseSupports(t) || t.emissionType !== "lifecycle" || !this.isLifecycleEvent(t, o) ? !1 : this.isEventPatternMatch(t, n, o);
|
|
@@ -865,8 +865,8 @@ class et extends C {
|
|
|
865
865
|
if (!s)
|
|
866
866
|
return !1;
|
|
867
867
|
try {
|
|
868
|
-
const i = o.getBlue(), c = i.nodeToJson(s),
|
|
869
|
-
return Oe(c,
|
|
868
|
+
const i = o.getBlue(), c = i.nodeToJson(s), h = i.nodeToJson(r);
|
|
869
|
+
return Oe(c, h);
|
|
870
870
|
} catch (i) {
|
|
871
871
|
return console.warn("Error during event pattern matching:", i), !1;
|
|
872
872
|
}
|
|
@@ -875,14 +875,14 @@ class et extends C {
|
|
|
875
875
|
class tt {
|
|
876
876
|
constructor() {
|
|
877
877
|
l(this, "contractType", "Operation");
|
|
878
|
-
l(this, "contractBlueId",
|
|
878
|
+
l(this, "contractBlueId", y.Operation);
|
|
879
879
|
l(this, "role", "adapter");
|
|
880
880
|
}
|
|
881
881
|
supports(e, t, n, o) {
|
|
882
882
|
const s = n.getBlue().nodeToSchemaOutput(t, be), i = this.parseEventPayload(e, n), c = this.isOperationNameMatch(
|
|
883
883
|
i,
|
|
884
884
|
o
|
|
885
|
-
),
|
|
885
|
+
), h = this.isOperationChannelMatch(
|
|
886
886
|
e,
|
|
887
887
|
s
|
|
888
888
|
), u = this.isRequestPatternMatch(
|
|
@@ -890,7 +890,7 @@ class tt {
|
|
|
890
890
|
s,
|
|
891
891
|
n
|
|
892
892
|
);
|
|
893
|
-
return c &&
|
|
893
|
+
return c && h && u;
|
|
894
894
|
}
|
|
895
895
|
async handle(e, t, n, o) {
|
|
896
896
|
n.emitEvent({
|
|
@@ -938,7 +938,7 @@ class nt {
|
|
|
938
938
|
constructor() {
|
|
939
939
|
l(this, "contractType", "Process Embedded");
|
|
940
940
|
l(this, "role", "adapter");
|
|
941
|
-
l(this, "contractBlueId",
|
|
941
|
+
l(this, "contractBlueId", y["Process Embedded"]);
|
|
942
942
|
}
|
|
943
943
|
supports(e) {
|
|
944
944
|
return e.source !== "channel";
|
|
@@ -952,8 +952,15 @@ class nt {
|
|
|
952
952
|
});
|
|
953
953
|
}
|
|
954
954
|
}
|
|
955
|
-
|
|
956
|
-
|
|
955
|
+
const ot = !process.env.SKIP_ISOLATED_VM;
|
|
956
|
+
let m = null;
|
|
957
|
+
if (ot)
|
|
958
|
+
try {
|
|
959
|
+
m = require("isolated-vm");
|
|
960
|
+
} catch {
|
|
961
|
+
console.warn("isolated-vm not available, using fallback evaluation method");
|
|
962
|
+
}
|
|
963
|
+
function rt(a) {
|
|
957
964
|
return /\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a) || /\bexport\s+/.test(a);
|
|
958
965
|
}
|
|
959
966
|
class A {
|
|
@@ -977,25 +984,18 @@ class A {
|
|
|
977
984
|
].join(`
|
|
978
985
|
`);
|
|
979
986
|
}
|
|
980
|
-
static async
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
}
|
|
988
|
-
} catch {
|
|
989
|
-
}
|
|
990
|
-
try {
|
|
991
|
-
const r = await import("isolated-vm").catch(() => null);
|
|
992
|
-
y = (r == null ? void 0 : r.default) ?? r;
|
|
993
|
-
} catch {
|
|
994
|
-
}
|
|
987
|
+
static async ensureIvm() {
|
|
988
|
+
if (m)
|
|
989
|
+
return m;
|
|
990
|
+
try {
|
|
991
|
+
typeof require == "function" ? m = require("isolated-vm") : m = (await import("isolated-vm")).default ?? await import("isolated-vm");
|
|
992
|
+
} catch (e) {
|
|
993
|
+
console.error(e), m = null;
|
|
995
994
|
}
|
|
995
|
+
return m;
|
|
996
996
|
}
|
|
997
997
|
/**
|
|
998
|
-
* Main evaluation method -
|
|
998
|
+
* Main evaluation method - chooses between secure and simple evaluation strategies
|
|
999
999
|
*/
|
|
1000
1000
|
static async evaluate({
|
|
1001
1001
|
code: e,
|
|
@@ -1003,7 +1003,7 @@ class A {
|
|
|
1003
1003
|
bindings: n = {},
|
|
1004
1004
|
options: o = {}
|
|
1005
1005
|
}) {
|
|
1006
|
-
if (await this.
|
|
1006
|
+
if (await this.ensureIvm(), !m)
|
|
1007
1007
|
throw new Error(this.getIvmUnavailableMessage());
|
|
1008
1008
|
return this.evaluateSecure(e, n, t, o);
|
|
1009
1009
|
}
|
|
@@ -1011,23 +1011,23 @@ class A {
|
|
|
1011
1011
|
* Secure evaluation using isolated-vm with support for ES modules
|
|
1012
1012
|
*/
|
|
1013
1013
|
static async evaluateSecure(e, t, n, o = {}) {
|
|
1014
|
-
if (!
|
|
1015
|
-
const r = new
|
|
1014
|
+
if (!m) throw new Error(this.getIvmUnavailableMessage());
|
|
1015
|
+
const r = new m.Isolate({ memoryLimit: 32 }), s = await r.createContext(), i = s.global;
|
|
1016
1016
|
try {
|
|
1017
1017
|
await this.setupIsolateEnvironment(i, t);
|
|
1018
|
-
const c = /* @__PURE__ */ new Map(),
|
|
1018
|
+
const c = /* @__PURE__ */ new Map(), h = this.createModuleResolver(
|
|
1019
1019
|
r,
|
|
1020
1020
|
s,
|
|
1021
1021
|
c,
|
|
1022
1022
|
n
|
|
1023
1023
|
);
|
|
1024
1024
|
let u;
|
|
1025
|
-
return
|
|
1025
|
+
return rt(e) ? u = await this.evaluateESModule(
|
|
1026
1026
|
r,
|
|
1027
1027
|
s,
|
|
1028
1028
|
e,
|
|
1029
1029
|
o,
|
|
1030
|
-
|
|
1030
|
+
h
|
|
1031
1031
|
) : u = await this.evaluateSimpleScript(
|
|
1032
1032
|
r,
|
|
1033
1033
|
s,
|
|
@@ -1045,18 +1045,18 @@ class A {
|
|
|
1045
1045
|
* Setup the isolated VM environment with necessary host functions and data
|
|
1046
1046
|
*/
|
|
1047
1047
|
static async setupIsolateEnvironment(e, t) {
|
|
1048
|
-
if (!
|
|
1049
|
-
const n = new
|
|
1048
|
+
if (!m) throw new Error("isolated-vm not available");
|
|
1049
|
+
const n = new m.Callback(
|
|
1050
1050
|
(...r) => console.log(...r)
|
|
1051
|
-
), o = new
|
|
1051
|
+
), o = new m.ExternalCopy({
|
|
1052
1052
|
log: n
|
|
1053
1053
|
}).copyInto();
|
|
1054
1054
|
await e.set("console", o);
|
|
1055
1055
|
for (const [r, s] of Object.entries(t))
|
|
1056
1056
|
typeof s == "function" ? await e.set(
|
|
1057
1057
|
r,
|
|
1058
|
-
new
|
|
1059
|
-
) : await e.set(r, new
|
|
1058
|
+
new m.Callback(s)
|
|
1059
|
+
) : await e.set(r, new m.ExternalCopy(s).copyInto());
|
|
1060
1060
|
}
|
|
1061
1061
|
/**
|
|
1062
1062
|
* Create module resolver function for handling imports
|
|
@@ -1070,11 +1070,11 @@ class A {
|
|
|
1070
1070
|
throw new Error(
|
|
1071
1071
|
`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`
|
|
1072
1072
|
);
|
|
1073
|
-
const c = await i(s),
|
|
1074
|
-
return n.set(r,
|
|
1073
|
+
const c = await i(s), h = await e.compileModule(c);
|
|
1074
|
+
return n.set(r, h), await h.instantiate(
|
|
1075
1075
|
t,
|
|
1076
1076
|
this.createModuleResolver(e, t, n, o)
|
|
1077
|
-
),
|
|
1077
|
+
), h;
|
|
1078
1078
|
}
|
|
1079
1079
|
if (/^https?:\/\//.test(r)) {
|
|
1080
1080
|
let s;
|
|
@@ -1111,14 +1111,14 @@ class A {
|
|
|
1111
1111
|
static async evaluateESModule(e, t, n, o, r) {
|
|
1112
1112
|
let s = n;
|
|
1113
1113
|
if (o.isCodeBlock) {
|
|
1114
|
-
const
|
|
1114
|
+
const h = /^\s*(import\s.+?;|export\s.+?;)/gm, u = (n.match(h) || []).join(
|
|
1115
1115
|
`
|
|
1116
1116
|
`
|
|
1117
|
-
),
|
|
1117
|
+
), d = n.replace(h, "").trim();
|
|
1118
1118
|
s = `
|
|
1119
1119
|
${u}
|
|
1120
1120
|
const run = function() {
|
|
1121
|
-
${
|
|
1121
|
+
${d}
|
|
1122
1122
|
};
|
|
1123
1123
|
export default run();
|
|
1124
1124
|
`;
|
|
@@ -1149,18 +1149,18 @@ class R {
|
|
|
1149
1149
|
* Creates standard bindings for workflow step execution
|
|
1150
1150
|
*/
|
|
1151
1151
|
static createStandardBindings(e, t, n) {
|
|
1152
|
-
const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s =
|
|
1152
|
+
const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s = J(r) ? r.toNumber() : r;
|
|
1153
1153
|
return {
|
|
1154
1154
|
document: (i) => {
|
|
1155
1155
|
const c = e.get(i);
|
|
1156
|
-
return
|
|
1156
|
+
return J(c) ? c.toNumber() : S(c) ? o.nodeToJson(c, "original") : c;
|
|
1157
1157
|
},
|
|
1158
1158
|
event: s,
|
|
1159
1159
|
steps: n
|
|
1160
1160
|
};
|
|
1161
1161
|
}
|
|
1162
1162
|
}
|
|
1163
|
-
const
|
|
1163
|
+
const st = /^\$\{([\s\S]*)\}$/, at = /\$\{([\s\S]*?)\}/, T = (a) => typeof a != "string" ? !1 : st.test(a), U = (a) => typeof a != "string" ? !1 : at.test(a), ce = (a) => {
|
|
1164
1164
|
if (!T(a))
|
|
1165
1165
|
throw new Error(`Invalid expression: ${a}`);
|
|
1166
1166
|
return a.slice(2, -1);
|
|
@@ -1203,12 +1203,12 @@ function Z(a, e) {
|
|
|
1203
1203
|
};
|
|
1204
1204
|
return o !== void 0 && (s.val = o), r !== void 0 && (s.from = r), e.jsonValueToNode(s);
|
|
1205
1205
|
}
|
|
1206
|
-
function
|
|
1206
|
+
function it(a) {
|
|
1207
1207
|
return a.jsonValueToNode({
|
|
1208
1208
|
type: "Document Processing Initiated"
|
|
1209
1209
|
});
|
|
1210
1210
|
}
|
|
1211
|
-
class
|
|
1211
|
+
class ct {
|
|
1212
1212
|
constructor() {
|
|
1213
1213
|
l(this, "stepType", "Update Document");
|
|
1214
1214
|
}
|
|
@@ -1227,17 +1227,17 @@ class it {
|
|
|
1227
1227
|
op: "replace",
|
|
1228
1228
|
path: "/changeset",
|
|
1229
1229
|
val: i
|
|
1230
|
-
}),
|
|
1231
|
-
for (const u of
|
|
1230
|
+
}), h = n.getBlue().nodeToSchemaOutput(c, j);
|
|
1231
|
+
for (const u of h.changeset ?? []) {
|
|
1232
1232
|
if (!u.path) continue;
|
|
1233
|
-
const
|
|
1233
|
+
const d = await this.evaluateChangePath(
|
|
1234
1234
|
u.path,
|
|
1235
1235
|
n,
|
|
1236
1236
|
t,
|
|
1237
1237
|
r
|
|
1238
1238
|
), p = u.val;
|
|
1239
1239
|
if ((u.op === "replace" || u.op === "add") && M(p)) {
|
|
1240
|
-
const
|
|
1240
|
+
const f = await this.evaluateChangeValue(
|
|
1241
1241
|
p,
|
|
1242
1242
|
n,
|
|
1243
1243
|
t,
|
|
@@ -1245,25 +1245,25 @@ class it {
|
|
|
1245
1245
|
);
|
|
1246
1246
|
n.addPatch({
|
|
1247
1247
|
op: u.op,
|
|
1248
|
-
path:
|
|
1249
|
-
val:
|
|
1248
|
+
path: d,
|
|
1249
|
+
val: f
|
|
1250
1250
|
}), n.emitEvent({
|
|
1251
1251
|
payload: Z(
|
|
1252
1252
|
{
|
|
1253
1253
|
op: u.op,
|
|
1254
|
-
path: n.resolvePath(
|
|
1255
|
-
val: s.nodeToJson(
|
|
1254
|
+
path: n.resolvePath(d),
|
|
1255
|
+
val: s.nodeToJson(f, "original")
|
|
1256
1256
|
},
|
|
1257
1257
|
s
|
|
1258
1258
|
),
|
|
1259
1259
|
emissionType: "update"
|
|
1260
1260
|
});
|
|
1261
1261
|
}
|
|
1262
|
-
u.op === "remove" && (n.addPatch({ op: u.op, path:
|
|
1262
|
+
u.op === "remove" && (n.addPatch({ op: u.op, path: d }), n.emitEvent({
|
|
1263
1263
|
payload: Z(
|
|
1264
1264
|
{
|
|
1265
1265
|
op: u.op,
|
|
1266
|
-
path: n.resolvePath(
|
|
1266
|
+
path: n.resolvePath(d),
|
|
1267
1267
|
val: null
|
|
1268
1268
|
},
|
|
1269
1269
|
s
|
|
@@ -1318,7 +1318,7 @@ class it {
|
|
|
1318
1318
|
return e;
|
|
1319
1319
|
}
|
|
1320
1320
|
}
|
|
1321
|
-
class
|
|
1321
|
+
class lt {
|
|
1322
1322
|
constructor() {
|
|
1323
1323
|
l(this, "stepType", "Trigger Event");
|
|
1324
1324
|
}
|
|
@@ -1335,7 +1335,7 @@ class ct {
|
|
|
1335
1335
|
});
|
|
1336
1336
|
}
|
|
1337
1337
|
}
|
|
1338
|
-
class
|
|
1338
|
+
class ut {
|
|
1339
1339
|
constructor() {
|
|
1340
1340
|
l(this, "stepType", "JavaScript Code");
|
|
1341
1341
|
}
|
|
@@ -1360,9 +1360,9 @@ class lt {
|
|
|
1360
1360
|
}
|
|
1361
1361
|
});
|
|
1362
1362
|
if (c && typeof c == "object" && "events" in c) {
|
|
1363
|
-
const
|
|
1364
|
-
if (Array.isArray(
|
|
1365
|
-
for (const u of
|
|
1363
|
+
const h = c;
|
|
1364
|
+
if (Array.isArray(h.events))
|
|
1365
|
+
for (const u of h.events)
|
|
1366
1366
|
n.emitEvent({
|
|
1367
1367
|
payload: s.jsonValueToNode(u),
|
|
1368
1368
|
emissionType: "triggered"
|
|
@@ -1371,15 +1371,15 @@ class lt {
|
|
|
1371
1371
|
return c;
|
|
1372
1372
|
}
|
|
1373
1373
|
}
|
|
1374
|
-
const
|
|
1375
|
-
new it(),
|
|
1374
|
+
const ht = [
|
|
1376
1375
|
new ct(),
|
|
1377
|
-
new lt()
|
|
1376
|
+
new lt(),
|
|
1377
|
+
new ut()
|
|
1378
1378
|
];
|
|
1379
1379
|
class le {
|
|
1380
|
-
constructor(e =
|
|
1380
|
+
constructor(e = ht) {
|
|
1381
1381
|
l(this, "contractType", "Sequential Workflow");
|
|
1382
|
-
l(this, "contractBlueId",
|
|
1382
|
+
l(this, "contractBlueId", y["Sequential Workflow"]);
|
|
1383
1383
|
l(this, "role", "handler");
|
|
1384
1384
|
l(this, "executors", []);
|
|
1385
1385
|
this.executors = e;
|
|
@@ -1398,20 +1398,20 @@ class le {
|
|
|
1398
1398
|
async handle(e, t, n, o) {
|
|
1399
1399
|
var i;
|
|
1400
1400
|
const r = {}, s = (i = t.getProperties()) == null ? void 0 : i.steps.getItems();
|
|
1401
|
-
for (const [c,
|
|
1402
|
-
const u = this.executors.find((p) => p.supports(
|
|
1401
|
+
for (const [c, h] of (s ?? []).entries()) {
|
|
1402
|
+
const u = this.executors.find((p) => p.supports(h));
|
|
1403
1403
|
if (!u)
|
|
1404
|
-
throw new Error(`Unsupported workflow step type "${
|
|
1405
|
-
const
|
|
1406
|
-
|
|
1404
|
+
throw new Error(`Unsupported workflow step type "${h.getType()}"`);
|
|
1405
|
+
const d = await u.execute(
|
|
1406
|
+
h,
|
|
1407
1407
|
e,
|
|
1408
1408
|
n,
|
|
1409
1409
|
o,
|
|
1410
1410
|
r
|
|
1411
1411
|
);
|
|
1412
|
-
if (
|
|
1413
|
-
const p =
|
|
1414
|
-
r[
|
|
1412
|
+
if (d !== void 0) {
|
|
1413
|
+
const p = h.getName(), f = typeof p == "string" ? p : `Step${c + 1}`;
|
|
1414
|
+
r[f] = d;
|
|
1415
1415
|
}
|
|
1416
1416
|
await n.flush();
|
|
1417
1417
|
}
|
|
@@ -1439,7 +1439,7 @@ class le {
|
|
|
1439
1439
|
class dt {
|
|
1440
1440
|
constructor(e) {
|
|
1441
1441
|
l(this, "contractType", "Sequential Workflow Operation");
|
|
1442
|
-
l(this, "contractBlueId",
|
|
1442
|
+
l(this, "contractBlueId", y["Sequential Workflow Operation"]);
|
|
1443
1443
|
l(this, "role", "handler");
|
|
1444
1444
|
l(this, "sequentialWorkflowProcessor");
|
|
1445
1445
|
this.sequentialWorkflowProcessor = e || new le();
|
|
@@ -1463,11 +1463,11 @@ class dt {
|
|
|
1463
1463
|
}
|
|
1464
1464
|
}
|
|
1465
1465
|
const ee = (a) => P.isTypeOf(a.payload, O);
|
|
1466
|
-
class
|
|
1466
|
+
class pt extends C {
|
|
1467
1467
|
constructor() {
|
|
1468
1468
|
super(...arguments);
|
|
1469
1469
|
l(this, "contractType", "Timeline Channel");
|
|
1470
|
-
l(this, "contractBlueId",
|
|
1470
|
+
l(this, "contractBlueId", y["Timeline Channel"]);
|
|
1471
1471
|
}
|
|
1472
1472
|
supports(t, n, o) {
|
|
1473
1473
|
var u;
|
|
@@ -1486,11 +1486,11 @@ class ht extends C {
|
|
|
1486
1486
|
});
|
|
1487
1487
|
}
|
|
1488
1488
|
}
|
|
1489
|
-
class
|
|
1489
|
+
class ft extends C {
|
|
1490
1490
|
constructor() {
|
|
1491
1491
|
super(...arguments);
|
|
1492
1492
|
l(this, "contractType", "Triggered Event Channel");
|
|
1493
|
-
l(this, "contractBlueId",
|
|
1493
|
+
l(this, "contractBlueId", y["Triggered Event Channel"]);
|
|
1494
1494
|
}
|
|
1495
1495
|
supports(t) {
|
|
1496
1496
|
return this.baseSupports(t) ? t.emissionType === "triggered" : !1;
|
|
@@ -1508,12 +1508,12 @@ const mt = [
|
|
|
1508
1508
|
// channels
|
|
1509
1509
|
new Ge(),
|
|
1510
1510
|
new Qe(),
|
|
1511
|
-
new
|
|
1511
|
+
new pt(),
|
|
1512
1512
|
new Ze(),
|
|
1513
1513
|
new et(),
|
|
1514
1514
|
new Xe(),
|
|
1515
1515
|
new Ye(),
|
|
1516
|
-
new
|
|
1516
|
+
new ft(),
|
|
1517
1517
|
new tt(),
|
|
1518
1518
|
// sequential workflows
|
|
1519
1519
|
new le(),
|
|
@@ -1521,7 +1521,7 @@ const mt = [
|
|
|
1521
1521
|
// markers
|
|
1522
1522
|
new Ke()
|
|
1523
1523
|
];
|
|
1524
|
-
class
|
|
1524
|
+
class bt {
|
|
1525
1525
|
/**
|
|
1526
1526
|
* Creates a new document processor
|
|
1527
1527
|
*
|
|
@@ -1563,7 +1563,7 @@ class Tt {
|
|
|
1563
1563
|
async initialize(e) {
|
|
1564
1564
|
let t = G(I(e), this.blue);
|
|
1565
1565
|
const n = {
|
|
1566
|
-
payload:
|
|
1566
|
+
payload: it(this.blue),
|
|
1567
1567
|
source: "internal",
|
|
1568
1568
|
emissionType: "lifecycle"
|
|
1569
1569
|
}, o = [n.payload];
|
|
@@ -1607,47 +1607,47 @@ class Tt {
|
|
|
1607
1607
|
for (; this.queue.length; ) {
|
|
1608
1608
|
if (++r > o)
|
|
1609
1609
|
throw new Error("Possible cycle – too many iterations");
|
|
1610
|
-
const i = this.queue.pop(), { nodePath: c, contractName:
|
|
1611
|
-
if (!S(p) || !((s = p.getContracts()) != null && s[
|
|
1612
|
-
const
|
|
1613
|
-
if (!
|
|
1614
|
-
console.warn(`No processor registered for contract: ${
|
|
1610
|
+
const i = this.queue.pop(), { nodePath: c, contractName: h, contractNode: u, event: d } = i, p = t.get(c);
|
|
1611
|
+
if (!S(p) || !((s = p.getContracts()) != null && s[h]) || !u.getType()) continue;
|
|
1612
|
+
const f = this.registry.get(u.getType());
|
|
1613
|
+
if (!f) {
|
|
1614
|
+
console.warn(`No processor registered for contract: ${h}`);
|
|
1615
1615
|
continue;
|
|
1616
1616
|
}
|
|
1617
|
-
const
|
|
1617
|
+
const v = new re(
|
|
1618
1618
|
() => t,
|
|
1619
1619
|
i,
|
|
1620
1620
|
this.blue,
|
|
1621
|
-
async (
|
|
1622
|
-
for (const
|
|
1623
|
-
if (
|
|
1621
|
+
async (w) => {
|
|
1622
|
+
for (const g of w)
|
|
1623
|
+
if (g.kind === "patch") {
|
|
1624
1624
|
const D = z(
|
|
1625
1625
|
t,
|
|
1626
1626
|
this.blue
|
|
1627
1627
|
);
|
|
1628
1628
|
for (const N of D) {
|
|
1629
|
-
const
|
|
1630
|
-
(
|
|
1629
|
+
const he = g.patch.op === "move" || g.patch.op === "copy" ? [g.patch.from, g.patch.path] : [g.patch.path], H = v.getNodePath(), de = he.some(
|
|
1630
|
+
(fe) => X(fe, N.absPath)
|
|
1631
1631
|
), pe = X(
|
|
1632
1632
|
H,
|
|
1633
1633
|
N.absPath
|
|
1634
1634
|
);
|
|
1635
|
-
if (
|
|
1635
|
+
if (de && !pe)
|
|
1636
1636
|
throw new ae(
|
|
1637
|
-
|
|
1637
|
+
g.patch,
|
|
1638
1638
|
N.absPath,
|
|
1639
1639
|
H
|
|
1640
1640
|
);
|
|
1641
1641
|
}
|
|
1642
1642
|
try {
|
|
1643
|
-
t = Q(t, [
|
|
1643
|
+
t = Q(t, [g.patch]);
|
|
1644
1644
|
} catch (N) {
|
|
1645
|
-
throw ze(
|
|
1645
|
+
throw ze(h, d, N), N;
|
|
1646
1646
|
}
|
|
1647
|
-
} else
|
|
1647
|
+
} else g.kind === "event" && (n.push(g.event.payload), await this.router.route(t, [], g.event, i.key[5]));
|
|
1648
1648
|
}
|
|
1649
1649
|
);
|
|
1650
|
-
await
|
|
1650
|
+
await f.handle(d, u, v, h), await v.flush();
|
|
1651
1651
|
}
|
|
1652
1652
|
return { state: t, emitted: n };
|
|
1653
1653
|
}
|
|
@@ -1673,11 +1673,11 @@ class ue {
|
|
|
1673
1673
|
return e;
|
|
1674
1674
|
}
|
|
1675
1675
|
}
|
|
1676
|
-
const
|
|
1676
|
+
const Pt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
1677
1677
|
__proto__: null,
|
|
1678
1678
|
ExpressionPreserver: ue
|
|
1679
1679
|
}, Symbol.toStringTag, { value: "Module" }));
|
|
1680
|
-
function
|
|
1680
|
+
function St() {
|
|
1681
1681
|
return new k.SequentialMergingProcessor([
|
|
1682
1682
|
new k.ValuePropagator(),
|
|
1683
1683
|
new ue(),
|
|
@@ -1688,7 +1688,7 @@ function Pt() {
|
|
|
1688
1688
|
]);
|
|
1689
1689
|
}
|
|
1690
1690
|
export {
|
|
1691
|
-
|
|
1691
|
+
bt as BlueDocumentProcessor,
|
|
1692
1692
|
He as ChannelEventCheckpointProcessor,
|
|
1693
1693
|
De as CodeBlockEvaluationError,
|
|
1694
1694
|
Xe as CompositeTimelineChannelProcessor,
|
|
@@ -1698,7 +1698,7 @@ export {
|
|
|
1698
1698
|
Ae as ExpressionEvaluationError,
|
|
1699
1699
|
Ke as InitializedMarkerProcessor,
|
|
1700
1700
|
Ye as LifecycleEventChannelProcessor,
|
|
1701
|
-
|
|
1701
|
+
Pt as MergingProcessors,
|
|
1702
1702
|
et as MyOSAgentChannelProcessor,
|
|
1703
1703
|
Ze as MyOSTimelineChannelProcessor,
|
|
1704
1704
|
tt as OperationProcessor,
|
|
@@ -1706,8 +1706,8 @@ export {
|
|
|
1706
1706
|
nt as ProcessEmbeddedProcessor,
|
|
1707
1707
|
dt as SequentialWorkflowOperationProcessor,
|
|
1708
1708
|
le as SequentialWorkflowProcessor,
|
|
1709
|
-
|
|
1710
|
-
|
|
1709
|
+
pt as TimelineChannelProcessor,
|
|
1710
|
+
ft as TriggeredEventChannelProcessor,
|
|
1711
1711
|
z as collectEmbeddedPathSpecs,
|
|
1712
|
-
|
|
1712
|
+
St as createDefaultMergingProcessor
|
|
1713
1713
|
};
|
|
@@ -19,9 +19,9 @@ export interface VMBindings {
|
|
|
19
19
|
*/
|
|
20
20
|
export declare class ExpressionEvaluator {
|
|
21
21
|
private static getIvmUnavailableMessage;
|
|
22
|
-
private static
|
|
22
|
+
private static ensureIvm;
|
|
23
23
|
/**
|
|
24
|
-
* Main evaluation method -
|
|
24
|
+
* Main evaluation method - chooses between secure and simple evaluation strategies
|
|
25
25
|
*/
|
|
26
26
|
static evaluate({ code, ctx, bindings, options, }: {
|
|
27
27
|
code: string;
|
|
@@ -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;
|
|
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,OAAO,CAAC,MAAM,CAAC,wBAAwB;mBA6BlB,SAAS;IAqB9B;;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;IASpB;;OAEG;mBACkB,cAAc;IAuDnC;;OAEG;mBACkB,uBAAuB;IA6B5C;;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.33.
|
|
3
|
+
"version": "1.33.3",
|
|
4
4
|
"dependencies": {
|
|
5
|
-
"@blue-labs/language": "1.33.
|
|
6
|
-
"@blue-labs/shared-utils": "1.33.
|
|
5
|
+
"@blue-labs/language": "1.33.3",
|
|
6
|
+
"@blue-labs/shared-utils": "1.33.3",
|
|
7
7
|
"isolated-vm": "^5.0.4"
|
|
8
8
|
},
|
|
9
9
|
"main": "./dist/index.js",
|