@blue-labs/document-processor 1.21.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/LICENSE +21 -0
- package/README.md +11 -0
- package/dist/BlueDocumentProcessor.d.ts +54 -0
- package/dist/BlueDocumentProcessor.d.ts.map +1 -0
- package/dist/config.d.ts +3 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/context.d.ts +21 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.mjs +1557 -0
- package/dist/processors/BaseChannelProcessor.d.ts +27 -0
- package/dist/processors/BaseChannelProcessor.d.ts.map +1 -0
- package/dist/processors/ChannelEventCheckpointProcessor.d.ts +13 -0
- package/dist/processors/ChannelEventCheckpointProcessor.d.ts.map +1 -0
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts +9 -0
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +1 -0
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts +9 -0
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +1 -0
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts +9 -0
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts.map +1 -0
- package/dist/processors/MyOSAgentChannelProcessor.d.ts +60 -0
- package/dist/processors/MyOSAgentChannelProcessor.d.ts.map +1 -0
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts +9 -0
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts.map +1 -0
- package/dist/processors/OperationProcessor.d.ts +11 -0
- package/dist/processors/OperationProcessor.d.ts.map +1 -0
- package/dist/processors/ProcessEmbeddedProcessor.d.ts +10 -0
- package/dist/processors/ProcessEmbeddedProcessor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +12 -0
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +15 -0
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/index.d.ts +2 -0
- package/dist/processors/SequentialWorkflowProcessor/index.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts +8 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts +8 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts +12 -0
- package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/types.d.ts +7 -0
- package/dist/processors/SequentialWorkflowProcessor/types.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts +12 -0
- package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts.map +1 -0
- package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts +59 -0
- package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts.map +1 -0
- package/dist/processors/TimelineChannelProcessor.d.ts +9 -0
- package/dist/processors/TimelineChannelProcessor.d.ts.map +1 -0
- package/dist/processors/index.d.ts +12 -0
- package/dist/processors/index.d.ts.map +1 -0
- package/dist/queue/TaskKey.d.ts +22 -0
- package/dist/queue/TaskKey.d.ts.map +1 -0
- package/dist/queue/TaskQueue.d.ts +31 -0
- package/dist/queue/TaskQueue.d.ts.map +1 -0
- package/dist/registry/ContractRegistry.d.ts +47 -0
- package/dist/registry/ContractRegistry.d.ts.map +1 -0
- package/dist/repo/core/blue-ids/index.d.ts +21 -0
- package/dist/repo/core/blue-ids/index.d.ts.map +1 -0
- package/dist/repo/core/index.d.ts +199 -0
- package/dist/repo/core/index.d.ts.map +1 -0
- package/dist/repo/core/schema/Channel.d.ts +13 -0
- package/dist/repo/core/schema/Channel.d.ts.map +1 -0
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts +17 -0
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts.map +1 -0
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts +17 -0
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts.map +1 -0
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts +17 -0
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts.map +1 -0
- package/dist/repo/core/schema/JavaScriptCode.d.ts +10 -0
- package/dist/repo/core/schema/JavaScriptCode.d.ts.map +1 -0
- package/dist/repo/core/schema/JsonPatchEntry.d.ts +22 -0
- package/dist/repo/core/schema/JsonPatchEntry.d.ts.map +1 -0
- package/dist/repo/core/schema/Operation.d.ts +16 -0
- package/dist/repo/core/schema/Operation.d.ts.map +1 -0
- package/dist/repo/core/schema/OperationRequest.d.ts +29 -0
- package/dist/repo/core/schema/OperationRequest.d.ts.map +1 -0
- package/dist/repo/core/schema/ProcessEmbedded.d.ts +10 -0
- package/dist/repo/core/schema/ProcessEmbedded.d.ts.map +1 -0
- package/dist/repo/core/schema/SequentialWorkflow.d.ts +13 -0
- package/dist/repo/core/schema/SequentialWorkflow.d.ts.map +1 -0
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts +15 -0
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts.map +1 -0
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts +13 -0
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts.map +1 -0
- package/dist/repo/core/schema/TimelineChannel.d.ts +17 -0
- package/dist/repo/core/schema/TimelineChannel.d.ts.map +1 -0
- package/dist/repo/core/schema/TimelineEntry.d.ts +25 -0
- package/dist/repo/core/schema/TimelineEntry.d.ts.map +1 -0
- package/dist/repo/core/schema/TriggerEvent.d.ts +10 -0
- package/dist/repo/core/schema/TriggerEvent.d.ts.map +1 -0
- package/dist/repo/core/schema/UpdateDocument.d.ts +40 -0
- package/dist/repo/core/schema/UpdateDocument.d.ts.map +1 -0
- package/dist/repo/core/schema/index.d.ts +15 -0
- package/dist/repo/core/schema/index.d.ts.map +1 -0
- package/dist/repo/myos/blue-ids/index.d.ts +8 -0
- package/dist/repo/myos/blue-ids/index.d.ts.map +1 -0
- package/dist/repo/myos/index.d.ts +101 -0
- package/dist/repo/myos/index.d.ts.map +1 -0
- package/dist/repo/myos/schema/MyOSAgent.d.ts +10 -0
- package/dist/repo/myos/schema/MyOSAgent.d.ts.map +1 -0
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts +30 -0
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts.map +1 -0
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts +19 -0
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts.map +1 -0
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts +24 -0
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts.map +1 -0
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts +32 -0
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts.map +1 -0
- package/dist/repo/myos/schema/index.d.ts +6 -0
- package/dist/repo/myos/schema/index.d.ts.map +1 -0
- package/dist/routing/EventRouter.d.ts +51 -0
- package/dist/routing/EventRouter.d.ts.map +1 -0
- package/dist/types.d.ts +86 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/CheckpointCache.d.ts +10 -0
- package/dist/utils/CheckpointCache.d.ts.map +1 -0
- package/dist/utils/EventTraceManager.d.ts +46 -0
- package/dist/utils/EventTraceManager.d.ts.map +1 -0
- package/dist/utils/TinyQueue.d.ts +12 -0
- package/dist/utils/TinyQueue.d.ts.map +1 -0
- package/dist/utils/checkpoint.d.ts +4 -0
- package/dist/utils/checkpoint.d.ts.map +1 -0
- package/dist/utils/document.d.ts +19 -0
- package/dist/utils/document.d.ts.map +1 -0
- package/dist/utils/exceptions.d.ts +28 -0
- package/dist/utils/exceptions.d.ts.map +1 -0
- package/dist/utils/fetchText.d.ts +2 -0
- package/dist/utils/fetchText.d.ts.map +1 -0
- package/dist/utils/logPatchError.d.ts +3 -0
- package/dist/utils/logPatchError.d.ts.map +1 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.d.ts.map +1 -0
- package/dist/utils/typeGuard.d.ts +5 -0
- package/dist/utils/typeGuard.d.ts.map +1 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 @blue-labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# document-processor
|
|
2
|
+
|
|
3
|
+
This library was generated with [Nx](https://nx.dev).
|
|
4
|
+
|
|
5
|
+
## Building
|
|
6
|
+
|
|
7
|
+
Run `nx build document-processor` to build the library.
|
|
8
|
+
|
|
9
|
+
## Running unit tests
|
|
10
|
+
|
|
11
|
+
Run `nx test document-processor` to execute the unit tests via [Vitest](https://vitest.dev/).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { ContractProcessor, DocumentNode, EventNodePayload, ProcessingResult } from './types';
|
|
2
|
+
import { Blue } from '@blue-labs/language';
|
|
3
|
+
/**
|
|
4
|
+
* BlueDocumentProcessor - Main orchestrator for document processing
|
|
5
|
+
*
|
|
6
|
+
* Orchestrates the document processing pipeline, managing state transitions
|
|
7
|
+
* and event propagation through the registered contract processors.
|
|
8
|
+
*/
|
|
9
|
+
export declare class BlueDocumentProcessor {
|
|
10
|
+
private readonly blue;
|
|
11
|
+
private taskCounter;
|
|
12
|
+
private eventCounter;
|
|
13
|
+
private readonly registry;
|
|
14
|
+
private readonly queue;
|
|
15
|
+
private readonly router;
|
|
16
|
+
private readonly checkpointCache;
|
|
17
|
+
/**
|
|
18
|
+
* Creates a new document processor
|
|
19
|
+
*
|
|
20
|
+
* @param processors - Initial list of processors to register
|
|
21
|
+
*/
|
|
22
|
+
constructor(blue: Blue, processors?: ContractProcessor[]);
|
|
23
|
+
/**
|
|
24
|
+
* Registers a new contract processor
|
|
25
|
+
*
|
|
26
|
+
* @param cp - The processor to register
|
|
27
|
+
* @param orderHint - Optional priority value for execution order
|
|
28
|
+
*/
|
|
29
|
+
register(cp: ContractProcessor, orderHint?: number): void;
|
|
30
|
+
/**
|
|
31
|
+
* Initializes a document and runs all init events
|
|
32
|
+
*
|
|
33
|
+
* @param document - The document to initialize
|
|
34
|
+
* @returns Processing result with final state and emitted events
|
|
35
|
+
*/
|
|
36
|
+
initialise(document: DocumentNode): Promise<ProcessingResult>;
|
|
37
|
+
/**
|
|
38
|
+
* Processes a batch of events against the document
|
|
39
|
+
*
|
|
40
|
+
* @param document - The document to process events against
|
|
41
|
+
* @param incoming - List of event payloads to process
|
|
42
|
+
* @returns Processing result with final state and emitted events
|
|
43
|
+
*/
|
|
44
|
+
processEvents(document: DocumentNode, incoming: EventNodePayload[]): Promise<ProcessingResult>;
|
|
45
|
+
/**
|
|
46
|
+
* Collects initialization events from contract processors
|
|
47
|
+
*/
|
|
48
|
+
private bootstrapContracts;
|
|
49
|
+
/**
|
|
50
|
+
* Drains the task queue and applies all actions
|
|
51
|
+
*/
|
|
52
|
+
private drainQueue;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=BlueDocumentProcessor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BlueDocumentProcessor.d.ts","sourceRoot":"","sources":["../src/BlueDocumentProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,YAAY,EAEZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAYjB,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAG3C;;;;;GAKG;AACH,qBAAa,qBAAqB;IAc9B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAbvB,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IAEzD;;;;OAIG;gBAEgB,IAAI,EAAE,IAAI,EAC3B,UAAU,GAAE,iBAAiB,EAAsB;IAkBrD;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,EAAE,iBAAiB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAIzD;;;;;OAKG;IACG,UAAU,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAYnE;;;;;;OAMG;IACG,aAAa,CACjB,QAAQ,EAAE,YAAY,EACtB,QAAQ,EAAE,gBAAgB,EAAE,GAC3B,OAAO,CAAC,gBAAgB,CAAC;IAyB5B;;OAEG;YACW,kBAAkB;IAoBhC;;OAEG;YACW,UAAU;CAmFzB"}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE5C,eAAO,MAAM,iBAAiB,EAAE,iBAAiB,EAehD,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DocumentNode, ProcessingContext, EventNode, ProcessingAction, HandlerTask, BlueNodeGetResult } from './types';
|
|
2
|
+
import { Blue, BlueNodePatch } from '@blue-labs/language';
|
|
3
|
+
export declare class InternalContext implements ProcessingContext {
|
|
4
|
+
private getDocument;
|
|
5
|
+
private taskInfo;
|
|
6
|
+
private blue;
|
|
7
|
+
private onFlush?;
|
|
8
|
+
private readonly actions;
|
|
9
|
+
constructor(getDocument: () => DocumentNode, taskInfo: HandlerTask, blue: Blue, onFlush?: ((actions: ProcessingAction[]) => Promise<void>) | undefined);
|
|
10
|
+
get(path: string): BlueNodeGetResult;
|
|
11
|
+
addPatch(patch: BlueNodePatch): void;
|
|
12
|
+
emitEvent(event: EventNode): void;
|
|
13
|
+
flush(): Promise<ProcessingAction[]>;
|
|
14
|
+
getNodePath(): string;
|
|
15
|
+
resolvePath(path: string): string;
|
|
16
|
+
getTaskInfo(): HandlerTask | undefined;
|
|
17
|
+
getBlue(): Blue;
|
|
18
|
+
loadExternalModule(url: string): Promise<string>;
|
|
19
|
+
loadBlueContent(blueId: string): Promise<string>;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,SAAS,EACT,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EAClB,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAE1D,qBAAa,eAAgB,YAAW,iBAAiB;IAIrD,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,OAAO,CAAC;IANlB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;gBAGxC,WAAW,EAAE,MAAM,YAAY,EAC/B,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,GAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,aAAA;IAGlE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB;IAMpC,QAAQ,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI;IAUpC,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAa3B,KAAK,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAQ1C,WAAW,IAAI,MAAM;IAIrB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAIjC,WAAW,IAAI,WAAW,GAAG,SAAS;IAItC,OAAO,IAAI,IAAI;IAMf,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAOhD,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CAGjD"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";var ge=Object.defineProperty;var Ee=(i,e,t)=>e in i?ge(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var l=(i,e,t)=>Ee(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("zod"),d=require("@blue-labs/language"),k=require("@blue-labs/shared-utils"),we=(i,e)=>({on:(t,n)=>({end:()=>n(null)})});async function Ce(i){return new Promise((e,t)=>{we().on("error",t).end()})}const P=(...i)=>i.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<i.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class L{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=P(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:P(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n]};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return P(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(e){if(!/^https?:\/\//.test(e))throw new Error("Only http/https URLs are allowed");return Ce()}loadBlueContent(e){throw new Error("Not implemented")}}class H extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class X extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class V extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class W extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}const m={Channel:"2RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc","Timeline Channel":"RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Composite Timeline Channel":"qxkh3uMkKoutP5DxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow":"h3uDxZ7dr6Eo27B7fuxMkKoutP5qxkQCS1VAptiCPc2R","Process Embedded":"DxZ7dr6EoMkKoutP5qxkh3u27B7fuxQCS1VAptiCPc2R","Embedded Node Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Document Update Channel":"MkKoutP5qxkh3uDQCS1VAptiCPc2xZ7dr6Eo27B7fux","Channel Event Checkpoint":"o27B7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Update Document":"7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Trigger Event":"kQCS1VAp7fuxMkKoutPh3uDxZ7dr6E5qxtiCPc2R","Json Patch Entry":"EnUQeMiMa2wHFW3JbeSPvdgfpL6qZYCR29m3SfeHsKSY","JavaScript Code":"MkKoutPDxZ7dr6Eo5qxkh3u27B7fuxQCS1VAptiCPc2R","Timeline Entry":"uDxZ7dr6Eo27B7fMkKoutP5qxkh3uxQCS1VAptiCPc2R",Operation:"OpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow Operation":"SeqOpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC","Operation Request":"OpReqKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC"},I=d.withTypeBlueId(m.Channel)(u.z.object({name:u.z.string().optional(),description:u.z.string().optional()})),Se=d.withTypeBlueId(m["Composite Timeline Channel"])(I.extend({channels:u.z.array(u.z.string()).optional()})),Pe=d.withTypeBlueId(m["Document Update Channel"])(I.extend({path:u.z.string().optional()})),R=d.withTypeBlueId(m["Embedded Node Channel"])(I.extend({path:u.z.string().optional()})),x=d.withTypeBlueId(m["JavaScript Code"])(u.z.object({code:u.z.string().optional()})),Te=d.withTypeBlueId(m.Operation)(u.z.object({request:d.blueNodeField().optional(),description:u.z.string().optional(),channel:u.z.string().optional()})),ve=d.withTypeBlueId(m["Operation Request"])(u.z.object({operation:u.z.string().optional(),request:d.blueNodeField(),document:u.z.object({blueId:u.z.string().optional()}).optional(),allowNewerVersion:u.z.boolean().optional()})),A=d.withTypeBlueId(m["Process Embedded"])(u.z.object({paths:u.z.array(u.z.string()).optional()})),z=d.withTypeBlueId(m["Sequential Workflow"])(u.z.object({steps:u.z.array(d.blueNodeField()).optional(),channel:u.z.string().optional()})),be=d.withTypeBlueId(m["Sequential Workflow Operation"])(z.omit({channel:!0}).extend({operation:u.z.string().optional()})),Y=d.withTypeBlueId(m["Timeline Channel"])(I.extend({timelineId:u.z.string().optional()})),O=d.withTypeBlueId(m["Timeline Entry"])(u.z.object({timelineId:u.z.string().optional(),timelinePrev:u.z.string().optional(),thread:u.z.string().optional(),threadPrev:u.z.string().optional(),message:d.blueNodeField().optional(),signature:u.z.string().optional()})),M=d.withTypeBlueId(m["Trigger Event"])(u.z.object({event:d.blueNodeField()})),ke=d.withTypeBlueId(m["Json Patch Entry"])(u.z.object({name:u.z.string().optional(),description:u.z.string().optional(),val:d.blueNodeField().optional(),op:u.z.string().optional(),path:u.z.string().optional()})),q=d.withTypeBlueId(m["Update Document"])(u.z.object({changeset:u.z.array(ke)}));function D(i,e,t="/",n=[]){const o=i.getContracts()??{};for(const[a,r]of Object.entries(o))if(d.BlueNodeTypeSchema.isTypeOf(r,A)){const h=e.nodeToSchemaOutput(r,A).paths??[];for(const p of h)n.push({absPath:P(t,p),contractPath:P(t,`contracts/${a}`)})}for(const[a,r]of Object.entries(i.getProperties()??{}))D(r,e,P(t,a),n);return n}function F(i,e){return i===e||i.startsWith(e.endsWith("/")?e:e+"/")}function Q(i,e){if(!e.length)return i;let t=i.clone();for(const n of e)try{t=d.applyBlueNodePatch(t,n,!0)}catch(o){throw new H(n,o)}return k.deepFreeze(t)}function g(i){return i!=null}function N(i){return i instanceof d.BlueNode}class Be{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const a=e-1>>1,r=t[a];if(n(o,r)>=0)break;t[e]=r,e=a}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,a=t[e];for(;e<o;){let r=(e<<1)+1;const s=r+1;if(s<this.length&&n(t[s],t[r])<0&&(r=s),n(t[r],a)>=0)break;t[e]=t[r],e=r}t[e]=a}}const Ne=(i,e,t,n,o,a)=>[-i,e,t,n,o,a],Ie=(i,e)=>{for(let t=0;t<i.key.length;t++){const n=i.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Oe{constructor(){l(this,"queue");this.queue=new Be([],Ie)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class xe{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}class Me{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED==="true"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=[...e.trace??[],this.makeHop(t,n)];return{...e,trace:o}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}}const qe=64;class Ae{constructor(e,t,n,o,a){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=a,this.traceManager=new Me}async route(e,t,n,o,a=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const h=n.dispatchPath.split("/").filter(Boolean),p={...n};return delete p.dispatchPath,this.route(e,h,p,o,a)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const h=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,h,n,o,a)}}const r=P("/",t.join("/")),s=e.get(r);N(s)&&await this.traverseContracts({doc:e,node:s,nodePath:r,event:n,afterTaskId:o,pathSegments:t,inlineDepth:a})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:a,afterTaskId:r,pathSegments:s,inlineDepth:c}=e;if(!this.shouldSkipForChannel(a,o))for(const[h,p]of Object.entries(n.getContracts()??{})){if(!p.getType())continue;const f=this.registry.get(p.getType());if(!f){console.warn(`No processor registered for contract: ${h}`);continue}const w={nodePath:o,contractName:h,contractNode:p,event:a},y=new L(()=>t,w,this.blue);if(f.supports(a,p,y,h))switch(f.role){case"adapter":await this.processAdapter({cp:f,event:a,contractNode:p,ctx:y,contractName:h,doc:t,afterTaskId:r,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:p,contractName:h,nodePath:o,event:a,depth:s.length,afterTaskId:r});break}}}async processAdapter(e){var C;const{cp:t,event:n,contractNode:o,ctx:a,contractName:r,doc:s,afterTaskId:c,inlineDepth:h}=e;if(h>=qe)throw new Error("Adapter recursion limit reached");const p=this.traceManager.addHop(n,((C=a.getTaskInfo())==null?void 0:C.nodePath)??"",r);await t.handle(p,o,a,r);const f=await a.flush();if(f.find(T=>T.kind==="patch"))throw new Error(`Contract "${r}" (adapter) attempted to patch the document`);const y=f.filter(T=>T.kind==="event");for(const T of y)await this.route(s,[],T.event,c,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:a,depth:r,afterTaskId:s}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(c),p=t.get("/order"),f=d.isBigNumber(p)?p.toNumber():0,w=this.getNextTaskId()+s,y=Ne(r,a.seq,h,f,n,w),C=this.traceManager.addHop(a,o,n);this.queue.push({key:y,nodePath:o,contractName:n,contractNode:t,event:C})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const ze=(i,e,t)=>{(t instanceof H||t instanceof X)&&console.error(`[Blue] Failed to apply patches for contract "${i}" on event ${JSON.stringify(e)}`,t)};function K(i,e){const t=i.clone(),n=o=>{var r;if(!N(o))return;const a=o.getContracts();a&&(!a.checkpoint||((r=a.checkpoint.getType())==null?void 0:r.getBlueId())!==m["Channel Event Checkpoint"])&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:m["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const a=t.get(o);N(a)&&n(a)}return k.deepFreeze(t)}class G{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",m["Channel Event Checkpoint"]);l(this,"role","handler");this.cache=e}supports(e){var t,n;return e.source==="channel"&&((t=e.rootEvent)==null?void 0:t.payload)===e.payload&&((n=e.rootEvent)==null?void 0:n.source)==="external"}async handle(e,t,n){var r;if(!e.channelName||!((r=e.rootEvent)!=null&&r.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),a=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(a,e,o)}init(){return[]}}const U=(i,e)=>i.get(e)!==void 0;class De{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:a}of this.firstSeen.values()){if(!o.channelName)continue;const r=P(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${r}/blueId`;U(e,r)?t.push({op:U(e,s)?"replace":"add",path:s,val:a}):t.push({op:"add",path:r,val:{blueId:a}})}return t}clear(){this.firstSeen.clear()}}class B{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}init(){return[]}}class ee extends B{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",m["Composite Timeline Channel"])}supports(t,n,o){const a=o.getBlue().nodeToSchemaOutput(n,Se);return!a.channels||!t.channelName?!1:a.channels.includes(t.channelName)}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class te extends B{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",m["Document Update Channel"])}supports(t,n,o,a){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,Pe),s=t.payload.path;if(!s||t.channelName===a)return!1;const c=r.path;return k.isNonNullable(c)&&s===o.resolvePath(c)}handle(t,n,o,a){const r=t.payload;r&&o.emitEvent({payload:r,channelName:a,source:"channel"})}}class ne extends B{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",m["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,R);return g(t.originNodePath)&&g(a.path)&&t.originNodePath===o.resolvePath(a.path)}handle(t,n,o,a){const r=o.getBlue().nodeToSchemaOutput(n,R),{originNodePath:s,payload:c}=t;g(r.path)&&s===o.resolvePath(r.path)&&o.emitEvent({payload:c,channelName:a,source:"channel"})}}const v={"MyOS Timeline Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","MyOS Timeline Entry":"uDxZ7dr6Eo2MkKoutP5qxkh3uxQCS1VAptiCPc2R7B7f","MyOS Agent":"AgentBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Channel":"AgentCh4nn3lBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Event":"AgentEv3ntBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V"},$e=d.withTypeBlueId(v["MyOS Timeline Channel"])(Y.extend({account:u.z.string().optional(),email:u.z.string().optional()})),je=d.withTypeBlueId(v["MyOS Timeline Entry"])(O.extend({account:u.z.string().optional(),email:u.z.string().optional()})),Ve=d.withTypeBlueId(v["MyOS Agent"])(u.z.object({agentId:u.z.string().optional()})),We=d.withTypeBlueId(v["MyOS Agent Channel"])(I.extend({agent:Ve.optional(),event:d.blueNodeField().optional()})),Re=d.withTypeBlueId(v["MyOS Agent Event"])(u.z.object({agentId:u.z.string().optional(),id:u.z.number().optional(),timestamp:u.z.number().optional(),event:d.blueNodeField().optional()})),J=i=>i.payload.type==="Timeline Entry"||i.payload.type==="MyOS Timeline Entry";class oe extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",v["MyOS Timeline Channel"])}supports(t,n,o){if(!this.baseSupports(t)||!J(t))return!1;const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,je),c=o.getBlue().nodeToSchemaOutput(n,$e),h=g(c.timelineId)&&g(s.timelineId),p=g(c.account)&&g(s.account),f=g(c.email)&&g(s.email);return h&&s.timelineId===c.timelineId||p&&s.account===c.account||f&&s.email===c.email}handle(t,n,o,a){J(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class ae extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",v["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:a,myosAgentChannel:r}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(a,r)&&this.isEventPatternMatch(a,r,o)}catch(a){return console.warn("Error in MyOSAgentChannelProcessor.supports:",a),!1}}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}parseEventAndChannel(t,n,o){const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,Re),c=a.nodeToSchemaOutput(n,We);return{myosAgentEvent:s,myosAgentChannel:c}}isAgentMatch(t,n){var r;const o=t.agentId,a=(r=n.agent)==null?void 0:r.agentId;return g(o)&&g(a)&&o===a}isEventPatternMatch(t,n,o){const a=n.event;if(!a)return!0;const r=t.event;if(!r)return!1;try{const s=o.getBlue(),c=s.nodeToJson(r),h=s.nodeToJson(a);return k.deepContains(c,h)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class re{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",m.Operation);l(this,"role","adapter")}supports(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,Te),s=this.parseEventPayload(e,n);return g(s==null?void 0:s.operation)&&s.operation===o&&e.source==="channel"&&e.channelName===r.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}init(){return[]}parseEventPayload(e,t){const n=t.getBlue(),o=n.jsonValueToNode(e.payload);if(d.BlueNodeTypeSchema.isTypeOf(o,O)){const a=n.nodeToSchemaOutput(o,O);if(a.message)return n.nodeToSchemaOutput(a.message,ve)}return null}}class se{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",m["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,A);for(const a of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(a)})}init(){return[]}}const ie=!process.env.SKIP_ISOLATED_VM;let S=null;if(ie)try{S=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function Z(i){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(i)||/\bexport\s+/.test(i)}class ce{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!S||!ie?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(Z(e))throw new Error("Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM.");try{if(n.isCodeBlock){const o=Object.keys(t);return await(await new Function(...o,`return async function codeBlock(${o.join(", ")}) { ${e} }`)(...o.map(s=>t[s])))(...o.map(s=>t[s]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new W(e,o):new V(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!S)throw new Error("isolated-vm not available");const a=new S.Isolate({memoryLimit:32}),r=await a.createContext(),s=r.global;try{await this.setupIsolateEnvironment(s,t);const c=new Map,h=this.createModuleResolver(a,r,c,n);return Z(e)?await this.evaluateESModule(a,r,e,o,h):await this.evaluateSimpleScript(a,r,e,t,o)}catch(c){throw o.isCodeBlock?new W(e,c):new V(e,c)}finally{r.release(),a.dispose()}}static async setupIsolateEnvironment(e,t){if(!S)throw new Error("isolated-vm not available");const n=new S.Callback((...o)=>console.log(...o));await e.set("log",n);for(const[o,a]of Object.entries(t))typeof a=="function"?await e.set(o,new S.Callback(a)):await e.set(o,new S.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async a=>{if(n.has(a))return n.get(a);if(a.startsWith("blue:")){const r=a.slice(5),s=o.loadBlueContent;if(typeof s!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${a})`);const c=await s(r),h=await e.compileModule(c);return n.set(a,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(a)){let r;if(typeof o.loadExternalModule=="function")r=await o.loadExternalModule(a);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${a})`);const s=await e.compileModule(r);return n.set(a,s),await s.instantiate(t,this.createModuleResolver(e,t,n,o)),s}throw new Error(`Unsupported module specifier "${a}"`)}}static async evaluateSimpleScript(e,t,n,o,a){const r=Object.keys(o).join(", "),s=Object.keys(o).map(p=>p),c=`(async (${r}) => { ${a.isCodeBlock?n:`return (${n});`} })(${s.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:a.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,a){let r=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,p=(n.match(h)||[]).join(`
|
|
2
|
+
`),f=n.replace(h,"").trim();r=`
|
|
3
|
+
${p}
|
|
4
|
+
const run = function() {
|
|
5
|
+
${f}
|
|
6
|
+
};
|
|
7
|
+
export default run();
|
|
8
|
+
`}const s=await e.compileModule(r);return await s.instantiate(t,a),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 le{static createStandardBindings(e,t,n){const o=e.getBlue();return{document:a=>{const r=e.get(a);return d.isBigNumber(r)?r.toNumber():N(r)?o.nodeToJson(r,"original"):r},event:t.payload,steps:n}}}class Fe{constructor(){l(this,"stepType","Update Document")}supports(e){return d.BlueNodeTypeSchema.isTypeOf(e,q)}async evaluateChangeValue(e,t,n,o){const a=e==null?void 0:e.getValue();if(typeof a=="string"&&a.startsWith("${")&&a.endsWith("}")){const r=a.slice(2,-1);return await ce.evaluate({code:r,ctx:t,bindings:le.createStandardBindings(t,n,o)})}return e}async execute(e,t,n,o,a){if(!d.BlueNodeTypeSchema.isTypeOf(e,q))return;const r=n.getBlue().nodeToSchemaOutput(e,q);for(const s of r.changeset??[])if(s.path){if(s.op==="replace"||s.op==="add"){const c=await this.evaluateChangeValue(s.val,n,t,a);n.addPatch({op:s.op,path:s.path,val:c}),n.emitEvent({payload:{type:"Document Update",op:s.op,path:n.resolvePath(s.path),val:c}})}s.op==="remove"&&(n.addPatch({op:s.op,path:s.path}),n.emitEvent({payload:{type:"Document Update",op:s.op,path:n.resolvePath(s.path),val:null}}))}}}class Qe{constructor(){l(this,"stepType","Trigger Event")}supports(e){return d.BlueNodeTypeSchema.isTypeOf(e,M)}async execute(e,t,n){const o=n.getBlue();if(!d.BlueNodeTypeSchema.isTypeOf(e,M))return;const a=o.nodeToSchemaOutput(e,M),r=o.nodeToJson(a.event,"original");n.emitEvent({payload:r})}}class Ke{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return d.BlueNodeTypeSchema.isTypeOf(e,x)}async execute(e,t,n,o,a){if(!d.BlueNodeTypeSchema.isTypeOf(e,x))return;const s=n.getBlue().nodeToSchemaOutput(e,x);if(!s.code)throw new Error("JavaScript code is required");const c=await ce.evaluate({code:s.code,ctx:n,bindings:le.createStandardBindings(n,t,a),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const h=c;if(Array.isArray(h.events))for(const p of h.events)n.emitEvent({payload:p})}return c}}const Ue=[new Fe,new Qe,new Ke];class ${constructor(e=Ue){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",m["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,z).channel;return e.source==="channel"&&e.channelName===r}async handle(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,z),s={},c=r.steps;for(const[h,p]of(c??[]).entries()){const f=this.executors.find(y=>y.supports(p));if(!f)throw new Error(`Unsupported workflow step type "${p.getType()}"`);const w=await f.execute(p,e,n,o,s);if(w!==void 0){const y=p.getName(),C=typeof y=="string"?y:`Step${h+1}`;s[C]=w}await n.flush()}}init(){return[]}}class ue{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",m["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new $}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,be).operation,s=e.channelName;return e.source==="channel"&&k.isNonNullable(s)&&k.isNonNullable(r)&&s===r}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(a){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",a),a}}}const _=i=>i.payload.type==="Timeline Entry";class he extends B{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",m["Timeline Channel"])}supports(t,n,o){if(!this.baseSupports(t)||!_(t))return!1;const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,O),c=o.getBlue().nodeToSchemaOutput(n,Y);return g(c.timelineId)&&g(s.timelineId)&&s.timelineId===c.timelineId}handle(t,n,o,a){_(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}const Je=[new se,new ne,new te,new he,new oe,new ae,new ee,new re,new $,new ue];class Ze{constructor(e,t=Je){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new De);this.blue=e,this.registry=new xe(t),this.queue=new Oe,this.router=new Ae(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new G(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialise(e){e=K(e,this.blue);const t=await this.bootstrapContracts(e);for(const n of t)await this.router.route(e,[],n,0);return this.drainQueue(e)}async processEvents(e,t){let n=K(e,this.blue);const o=[];for(const a of t)try{const r={payload:a,source:"external"};await this.router.route(n,[],r,0);const s=await this.drainQueue(n);n=s.state,o.push(...s.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=Q(n,c))}finally{this.checkpointCache.clear()}return{state:n,emitted:o}}async bootstrapContracts(e){const t=[],n=e.getContracts();if(!n)return t;for(const[,o]of Object.entries(n)){const a=this.registry.get(o.getType());a!=null&&a.init&&t.push(...await a.init(o))}return t}async drainQueue(e){var r;let t=e;const n=[],o=1e4;let a=0;for(;this.queue.length;){if(++a>o)throw new Error("Possible cycle – too many iterations");const s=this.queue.pop(),{nodePath:c,contractName:h,contractNode:p,event:f}=s,w=t.get(c);if(!N(w)||!((r=w.getContracts())!=null&&r[h])||!p.getType())continue;const y=this.registry.get(p.getType());if(!y){console.warn(`No processor registered for contract: ${h}`);continue}const C=new L(()=>t,s,this.blue,async T=>{for(const E of T)if(E.kind==="patch"){const de=D(t,this.blue);for(const b of de){const pe=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],j=C.getNodePath(),me=pe.some(ye=>F(ye,b.absPath)),fe=F(j,b.absPath);if(me&&!fe)throw new X(E.patch,b.absPath,j)}try{t=Q(t,[E.patch])}catch(b){throw ze(h,f,b),b}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,s.key[5]))});await y.handle(f,p,C,h),await C.flush()}return{state:t,emitted:n}}}exports.BlueDocumentProcessor=Ze;exports.ChannelEventCheckpointProcessor=G;exports.CompositeTimelineChannelProcessor=ee;exports.DocumentUpdateChannelProcessor=te;exports.EmbeddedNodeChannelProcessor=ne;exports.MyOSAgentChannelProcessor=ae;exports.MyOSTimelineChannelProcessor=oe;exports.OperationProcessor=re;exports.ProcessEmbeddedProcessor=se;exports.SequentialWorkflowOperationProcessor=ue;exports.SequentialWorkflowProcessor=$;exports.TimelineChannelProcessor=he;
|