@onereach/step-initialize-state-manager 1.0.0-framework.11
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/README.md +3 -0
- package/dist/index.d.mts +189 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +56 -0
package/README.md
ADDED
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { LoadedStateMachineInstance } from "@onereach/state-machine-step-service";
|
|
2
|
+
import { CONFIG, IActionEvent, ICacheFacade, IEvent, IStepId, IThread, IThreadId, LOCAL, RESULT } from "@onereach/flow-sdk/types/index.js";
|
|
3
|
+
import * as z from "zod/mini";
|
|
4
|
+
import { Step } from "@onereach/flow-sdk/step.js";
|
|
5
|
+
//#region src/schemas/data-in.d.ts
|
|
6
|
+
declare const dataInSchema: z.ZodMiniObject<{
|
|
7
|
+
stateTemplateId: z.ZodMiniString<string>;
|
|
8
|
+
handleMissingTemplate: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
|
|
9
|
+
stateId: z.ZodMiniString<string>;
|
|
10
|
+
stateTtl: z.ZodMiniOptional<z.ZodMiniObject<{
|
|
11
|
+
input: z.ZodMiniString<string>;
|
|
12
|
+
outputMode: z.ZodMiniEnum<{
|
|
13
|
+
ms: "ms";
|
|
14
|
+
s: "s";
|
|
15
|
+
m: "m";
|
|
16
|
+
h: "h";
|
|
17
|
+
d: "d";
|
|
18
|
+
}>;
|
|
19
|
+
}, z.core.$strip>>;
|
|
20
|
+
customizeInitialValue: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
|
|
21
|
+
useSharedState: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
|
|
22
|
+
handleStateChange: z.ZodMiniOptional<z.ZodMiniBoolean<boolean>>;
|
|
23
|
+
handleSharedStateChange: z.ZodMiniOptional<z.ZodMiniArray<z.ZodMiniEnum<{
|
|
24
|
+
local: "local";
|
|
25
|
+
remote: "remote";
|
|
26
|
+
}>>>;
|
|
27
|
+
processError: z.ZodMiniBoolean<boolean>;
|
|
28
|
+
processTimeout: z.ZodMiniBoolean<boolean>;
|
|
29
|
+
timeoutDuration: z.ZodMiniString<string>;
|
|
30
|
+
_testSettings: z.ZodMiniOptional<z.ZodMiniObject<{
|
|
31
|
+
cache: z.ZodMiniOptional<z.ZodMiniCustom<ICacheFacade, ICacheFacade>>;
|
|
32
|
+
}, z.core.$strip>>;
|
|
33
|
+
}, z.core.$strip>;
|
|
34
|
+
type DataIn = z.infer<typeof dataInSchema>;
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/threads/base/types.d.ts
|
|
37
|
+
interface BaseConfig extends CONFIG {
|
|
38
|
+
dataIn: DataIn;
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/threads/base/base.d.ts
|
|
42
|
+
declare class BaseStep<T extends BaseConfig> extends Step<T> {
|
|
43
|
+
resolveDataIn(): Promise<{
|
|
44
|
+
stateTemplateId: string;
|
|
45
|
+
stateId: string;
|
|
46
|
+
processError: boolean;
|
|
47
|
+
processTimeout: boolean;
|
|
48
|
+
timeoutDuration: string;
|
|
49
|
+
handleMissingTemplate?: boolean | undefined;
|
|
50
|
+
stateTtl?: {
|
|
51
|
+
input: string;
|
|
52
|
+
outputMode: "ms" | "s" | "m" | "h" | "d";
|
|
53
|
+
} | undefined;
|
|
54
|
+
customizeInitialValue?: boolean | undefined;
|
|
55
|
+
useSharedState?: boolean | undefined;
|
|
56
|
+
handleStateChange?: boolean | undefined;
|
|
57
|
+
handleSharedStateChange?: ("local" | "remote")[] | undefined;
|
|
58
|
+
_testSettings?: {
|
|
59
|
+
cache?: import("@onereach/flow-sdk/types/cache.js").ICacheFacade | undefined;
|
|
60
|
+
} | undefined;
|
|
61
|
+
}>;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/threads/main/types.d.ts
|
|
65
|
+
type InitializeStateMachineState = {
|
|
66
|
+
cancelled: boolean;
|
|
67
|
+
contentReady: boolean;
|
|
68
|
+
};
|
|
69
|
+
type InitializeStateMachineOut = LoadedStateMachineInstance['instance'];
|
|
70
|
+
interface InitializeStateMachineConfig extends BaseConfig {
|
|
71
|
+
dataOut: InitializeStateMachineOut;
|
|
72
|
+
state: InitializeStateMachineState;
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/utils/thread-utilities.d.ts
|
|
76
|
+
type ManagedThreadLocal = {
|
|
77
|
+
active: boolean;
|
|
78
|
+
parent: IThreadId;
|
|
79
|
+
};
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/threads/base/child-types.d.ts
|
|
82
|
+
type BaseChildResultCancel = {
|
|
83
|
+
status: 'cancel';
|
|
84
|
+
};
|
|
85
|
+
type BaseChildResult = BaseChildResultCancel | Error;
|
|
86
|
+
type BaseChildLocal = ManagedThreadLocal;
|
|
87
|
+
interface BaseChildConfig<TResult extends RESULT<CONFIG> = BaseChildResult, TLocal extends LOCAL<CONFIG> = BaseChildLocal> extends BaseConfig {
|
|
88
|
+
result: TResult;
|
|
89
|
+
local: TLocal;
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/threads/change-listener/listener/constants.d.ts
|
|
93
|
+
declare const changeListenerClassId = "cng_lnr";
|
|
94
|
+
declare const changeListenerEvents: {
|
|
95
|
+
readonly stateChanged: "st_cgd";
|
|
96
|
+
};
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/threads/change-listener/listener/types.d.ts
|
|
99
|
+
type ChangeListenerChange = {
|
|
100
|
+
change: LoadedStateMachineInstance;
|
|
101
|
+
type: 'local' | 'remote';
|
|
102
|
+
};
|
|
103
|
+
type ChangeListenerState = {
|
|
104
|
+
class: typeof changeListenerClassId;
|
|
105
|
+
changes: ChangeListenerChange[];
|
|
106
|
+
};
|
|
107
|
+
type ChangeListenerEventName = typeof changeListenerEvents;
|
|
108
|
+
type ChangeListenerLocalChangeEvent = IEvent<unknown, ChangeListenerEventName['stateChanged']>;
|
|
109
|
+
type ChangeListenerRemoteChangeEventName = `sm/${string}/${string}`;
|
|
110
|
+
type ChangeListenerRemoteChangeEvent = IEvent<unknown, ChangeListenerRemoteChangeEventName>;
|
|
111
|
+
type ChangeListenerEvents = ChangeListenerLocalChangeEvent | ChangeListenerRemoteChangeEvent;
|
|
112
|
+
interface ChangeListenerConfig extends BaseChildConfig {
|
|
113
|
+
events: ChangeListenerEvents;
|
|
114
|
+
state: ChangeListenerState;
|
|
115
|
+
dataOut: InitializeStateMachineOut;
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/threads/change-listener/worker/constants.d.ts
|
|
119
|
+
declare const changeListenerWorkerClassId = "chg_wrk";
|
|
120
|
+
declare const changeListenerWorkerExits: {
|
|
121
|
+
readonly local: "local change";
|
|
122
|
+
readonly remote: "remote change";
|
|
123
|
+
};
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/threads/change-listener/worker/types.d.ts
|
|
126
|
+
type ChangeListenerWorkerOut = InitializeStateMachineOut;
|
|
127
|
+
type ChangeListenerWorkerState = {
|
|
128
|
+
class: typeof changeListenerWorkerClassId;
|
|
129
|
+
change: ChangeListenerChange;
|
|
130
|
+
};
|
|
131
|
+
type ChangeListenerWorkerResult = undefined | RESULT<BaseChildConfig>;
|
|
132
|
+
interface ChangeListenerWorkerConfig extends BaseChildConfig<ChangeListenerWorkerResult> {
|
|
133
|
+
dataOut: ChangeListenerWorkerOut;
|
|
134
|
+
state: ChangeListenerWorkerState;
|
|
135
|
+
}
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/threads/change-listener/listener/change-listener.d.ts
|
|
138
|
+
declare class ChangeListener extends BaseStep<ChangeListenerConfig> {
|
|
139
|
+
static readonly class = "cng_lnr";
|
|
140
|
+
static start(thread: IThread<InitializeStateMachineConfig>): Promise<void>;
|
|
141
|
+
static stop<TConfig extends CONFIG>(thread: IThread<TConfig>): Promise<void>;
|
|
142
|
+
static getThreadId(stepId: IStepId): IThreadId;
|
|
143
|
+
private get stateMachine();
|
|
144
|
+
private get instanceTtl();
|
|
145
|
+
private get remoteChangeEventName();
|
|
146
|
+
private handleChange;
|
|
147
|
+
private shouldHandleStateChange;
|
|
148
|
+
/**
|
|
149
|
+
* Processes the next change in the listener thread's queue.
|
|
150
|
+
* If the worker thread is busy, it skips processing.
|
|
151
|
+
* If the event is the termination marker, it notifies the end of the controller thread.
|
|
152
|
+
* If the event is ready for processing, it starts the worker thread to handle it.
|
|
153
|
+
*/
|
|
154
|
+
private tryRunWorker;
|
|
155
|
+
runStep(): void;
|
|
156
|
+
initialize(): void;
|
|
157
|
+
onLocalStateChange(event: ChangeListenerLocalChangeEvent): Promise<void>;
|
|
158
|
+
onRemoteStateChange(event: ChangeListenerRemoteChangeEvent): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* Handler of the worker thread end event.
|
|
161
|
+
*/
|
|
162
|
+
onWorkerThreadEnd(event: IActionEvent<ChangeListenerWorkerConfig, 'end'>): void;
|
|
163
|
+
}
|
|
164
|
+
//#endregion
|
|
165
|
+
//#region src/threads/change-listener/worker/change-listener-worker.d.ts
|
|
166
|
+
declare class ChangeListenerWorker extends BaseStep<ChangeListenerWorkerConfig> {
|
|
167
|
+
static readonly class = "chg_wrk";
|
|
168
|
+
static start(thread: IThread<ChangeListenerConfig>, change: ChangeListenerChange): Promise<void>;
|
|
169
|
+
static isBusy(thread: IThread<ChangeListenerConfig>): boolean;
|
|
170
|
+
static getThreadId(stepId: IStepId): IThreadId;
|
|
171
|
+
runStep(): void;
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/threads/main/step.d.ts
|
|
175
|
+
declare class InitializeStateMachineStep extends BaseStep<InitializeStateMachineConfig> {
|
|
176
|
+
private validateMergeFieldType;
|
|
177
|
+
private get stateMachine();
|
|
178
|
+
private get instanceTtl();
|
|
179
|
+
runStep(): Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
//#region src/index.d.ts
|
|
183
|
+
declare const states: {
|
|
184
|
+
cng_lnr: typeof ChangeListener;
|
|
185
|
+
chg_wrk: typeof ChangeListenerWorker;
|
|
186
|
+
};
|
|
187
|
+
//#endregion
|
|
188
|
+
export { type BaseConfig, ChangeListener, ChangeListenerWorker, type InitializeStateMachineConfig, type InitializeStateMachineOut, type InitializeStateMachineState, InitializeStateMachineStep, InitializeStateMachineStep as step, changeListenerClassId, changeListenerEvents, changeListenerWorkerClassId, changeListenerWorkerExits, states };
|
|
189
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/schemas/data-in.ts","../src/threads/base/types.ts","../src/threads/base/base.ts","../src/threads/main/types.ts","../src/utils/thread-utilities.ts","../src/threads/base/child-types.ts","../src/threads/change-listener/listener/constants.ts","../src/threads/change-listener/listener/types.ts","../src/threads/change-listener/worker/constants.ts","../src/threads/change-listener/worker/types.ts","../src/threads/change-listener/listener/change-listener.ts","../src/threads/change-listener/worker/change-listener-worker.ts","../src/threads/main/step.ts","../src/index.ts"],"mappings":";;;;;cAea,cAAY,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BvB,EAAA,KAAA;KAEU,SAAS,EAAE,aAAa;;;UCxCnB,mBAAmB;EAClC,QAAQ;;;;cCGG,SAAS,UAAU,oBAAoB,KAAK;EAE1C,iBAAa;;;;;;;;;;;;;;;;;;;;;;KCNhB;EACV;EACA;;KAGU,4BAA4B;UAEvB,qCAAqC;EACpD,SAAS;EACT,OAAO;;;;KC4FG;EACV;EACA,QAAQ;;;;KCrGE;EACV;;KAEU,kBAAkB,wBAAwB;KAE1C,iBAAiB;UAEZ,gBACf,gBAAgB,OAAO,UAAU,iBACjC,eAAe,MAAM,UAAU,wBACvB;EACR,QAAQ;EACR,OAAO;;;;cClBI;cAEA;WAAA;;;;KCMD;EACV,QAAQ;EACR;;KAGU;EACV,cAAc;EAEd,SAAS;;KAGC,iCAAiC;KACjC,iCAAiC,gBAAgB;KACjD;KACA,kCAAkC,gBAAgB;KAClD,uBAAuB,iCAAiC;UAEnD,6BAA6B;EAC5C,QAAQ;EACR,OAAO;EAGP,SAAS;;;;cC9BE;cAEA;WAAA;WAAA;;;;KCMD,0BAA0B;KAE1B;EACV,cAAc;EAEd,QAAQ;;KAGE,yCAAyC,OAAO;UAE3C,mCAAmC,gBAAgB;EAClE,SAAS;EACT,OAAO;;;;cCSI,uBAAuB,SAAS;kBACpB;SAEH,MAAM,QAAQ,QAAQ,gCAAgC;SAiBtD,KAAK,gBAAgB,QAAQ,QAAQ,QAAQ,WAAW;SAI9D,YAAY,QAAQ,UAAU;cAMhC;cAQA;cAKA;UAME;UAqCN;;;;;;;UAcA;EAgBD;EAuBA;EAKM,mBAAmB,OAAO,iCAAiC;EAO3D,oBAAoB,OAAO,kCAAkC;;;;EAUnE,kBAAkB,OAAO,aAAa;;;;cClLlC,6BAA6B,SAAS;kBAC1B;SAEH,MAAM,QAAQ,QAAQ,uBAAuB,QAAQ,uBAAuB;SAYlF,OAAO,QAAQ,QAAQ;SAIvB,YAAY,QAAQ,UAAU;EAOrC;;;;cCxBI,mCAAmC,SAAS;UAC/C;cAQI;cAWA;EAMC,WAAW;;;;cC/Bb;kBAAA;kBAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";import{install as t}from"source-map-support";import{NotFoundError as n,StateMachineThreadService as r}from"@onereach/state-machine-step-service";import{setImmediate as i}from"node:timers/promises";import a from"timestring";import{ACTION as o}from"@onereach/flow-sdk/types/index.js";import{TimeoutError as s}from"@onereach/flow-sdk/errors/timeout.js";import*as c from"zod/mini";import{BasicError as l}from"@onereach/flow-sdk/errors/base.js";import{Step as u}from"@onereach/flow-sdk/step.js";import{readFile as d}from"node:fs/promises";const f={UNKNOWN:`UNKNOWN`,STEP_LOGIC_ISSUE:`STEP_LOGIC_ISSUE`,TIMEOUT:`TIMEOUT`,VALIDATION:`VALIDATION`,SERVER_ERROR:`SERVER_ERROR`,UNSUPPORTED:`UNSUPPORTED`};var p=class extends l{};c.config(c.locales.en());const m=[p,s];function h(e,t={}){let{preserveErrors:n=m,unknownMessage:r=`Unknown error`,unknownCode:i=f.UNKNOWN}=t;if(n?.some(t=>e instanceof t))return e;if(e instanceof c.core.$ZodError)return new p(c.prettifyError(e),e,{code:f.VALIDATION});if(typeof e==`string`)return new p(e,{code:f.UNKNOWN});if(e instanceof Error){if(e.message.includes(`Request timed out`))return new s(`Timeout`,e,{code:f.TIMEOUT});let t=e?.response?.data?.error?.message;return t==null?new p(r,e,{code:i}):new p(t,e,{code:f.SERVER_ERROR})}return new p(r,{code:i,data:e})}function g(e,t){function n(t,n,r,i){let a=e(t,n,r,i);if(typeof a==`function`){let e=i.value,t=a;if(e?.name!=null)try{Object.defineProperty(t,"name",{value:e.name})}catch{}return i.value=t,i}return a??i}return function(e,r,i){if(e!==null&&i!==null&&typeof e==`object`&&typeof i==`object`&&(typeof r==`string`||typeof r==`symbol`))return n(t,e,r,i);let a=e??t;return(e,t,r)=>n(a,e,t,r)}}const _=g((e,t,n,r)=>{let i=r.value;if(!(!i||typeof i!=`function`))return function(...t){try{let r=i.apply(this,t);return r instanceof Promise?r.catch(t=>v.call(this,e,t,n)):r}catch(t){return v.call(this,e,t,n)}}},{allowHandleError:!1,useErrorFilter:!0});function v(e,t,n){let r=n.toString();this.log.DEBUG?.(`Error in method '${r}'`,t);let i=e.useErrorFilter?h(t):t;if(i instanceof Error){if(e.allowHandleError){this.thread.enqueue({name:o.error,error:i});return}this.end(i);return}throw i}async function y(e,{id:t,state:n,local:r,...i},{force:a}={}){let s=e.process.getThread(t);if(e.log.DEBUG?.(`runThread: thread with id '${t}'`,i),s==null)return await e.thread.runThread({...i,id:t,state:n,local:{...r,parent:e.thread.id,active:!0}});if(!a&&!s.ended&&s.local.active)throw Error(`Thread with id '${t}' has not ended yet, cannot start it again`);if(n==null)throw Error(`Thread with id '${t}' must have a state to run`);return s.local.active=!0,await s.enqueueAndRun({name:o.goto,state:{...n,active:!0}})}function b(e,t){let n=e.process.getThread(t);return n!=null&&n.local.active&&!n.ended}function x(e,t=e.id){let n=[];for(let r in e.process.threads){let i=e.process.threads[r];i?.local.parent===t&&n.push(i)}return n}async function S(e,t,{result:n,stopChildThreads:r}={}){let i=e.process.getThread(t);e.log.DEBUG?.(`stopThread: thread with id '${t}'`),i&&(r&&await C(i,n),i.local.active&&(i.local.active=!1,!i.ended&&await i.enqueueAndRun({name:o.ending,result:n})))}async function C(e,t,n={}){let r=x(e).map(async n=>await S(e,n.id,{stopChildThreads:!0,result:t})),i=await Promise.allSettled(r);if(n.throw??!0){let e=i.find(e=>e.status===`rejected`);if(e)throw e.reason}return i}const w=g((e,t,n,r)=>{let i=r.value;if(!(!i||typeof i!=`function`))return function(...e){try{let t=i.apply(this,e);return t instanceof Promise?t.catch(e=>{let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),h(e)}):t}catch(e){let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),h(e)}}},{});c.config(c.locales.en());const T=c.string().check(c.trim(),c.refine(e=>![`undefined`,`null`].includes(e),{error:`Unexpected undefined or null merge-field value`})),E=c.object({stateTemplateId:T.check(c.minLength(1),c.maxLength(64)),handleMissingTemplate:c.optional(c.boolean()),stateId:T.check(c.minLength(1),c.maxLength(64)),stateTtl:c.optional(c.object({input:T,outputMode:c.enum([`ms`,`s`,`m`,`h`,`d`])})),customizeInitialValue:c.optional(c.boolean()),useSharedState:c.optional(c.boolean()),handleStateChange:c.optional(c.boolean()),handleSharedStateChange:c.optional(c.array(c.enum([`local`,`remote`]))),processError:c.boolean(),processTimeout:c.boolean(),timeoutDuration:T.check(c.trim(),c.minLength(1)),_testSettings:c.optional(c.object({cache:c.optional(c.custom())}))});function D(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function O(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var k=class extends u{async resolveDataIn(){let e=await super.resolveDataIn();return E.parse(e)}};O([w,D(`design:type`,Function),D(`design:paramtypes`,[]),D(`design:returntype`,Promise)],k.prototype,`resolveDataIn`,null);const A=`sm_mgr`,j=`chg_wrk`,M={local:`local change`,remote:`remote change`};var N=class extends k{static class=j;static async start(e,t){await y(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class,change:t}})}static isBusy(e){return b(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${A}_${this.class}_${e}`}runStep(){if(this.state.change==null)throw new p(`Change listener worker thread state must contain an instance to process`,{code:f.STEP_LOGIC_ISSUE});let{change:e}=this.state;this.log.DEBUG?.(`Executing change listener worker thread`,e),this.exitStep(M[e.type],e.change.instance)}};O([w,D(`design:type`,Function),D(`design:paramtypes`,[]),D(`design:returntype`,void 0)],N.prototype,`runStep`,null);const P=`cng_lnr`,F={stateChanged:`st_cgd`};var I=class extends k{static class=P;static async start(e){await y(e,{id:this.getThreadId(e.step.id),state:{step:e.step.id,class:this.class,changes:[]},background:!0},{force:!0})}static async stop(e){await S(e,this.getThreadId(e.step.id))}static getThreadId(e){return`${A}_${this.class}_${e}`}get stateMachine(){return new r(this.thread,{cache:this.data._testSettings?.cache,instanceTtl:this.instanceTtl}).stateMachine}get instanceTtl(){let{stateTtl:e}=this.data;return e?.input?a(e.input,e.outputMode):void 0}get remoteChangeEventName(){let{stateTemplateId:e,stateId:t}=this.data;return`sm/${e}/${t}`}async handleChange(e){let{stateId:t}=this.data,n=await this.stateMachine.load({id:t});if(n==null)return;let r=await this.getDataOut();if(r==null)throw new p(`Data out is not set`,{code:f.STEP_LOGIC_ISSUE});if(n.instance.sequence===r.sequence){this.log.WARN?.(`Skip change processing. Sequence is the same`,{sequence:n.instance.sequence});return}if(await this.setDataOut(n?.instance),this.shouldHandleStateChange(e)){this.state.changes.push({change:n,type:e}),await i(),this.tryRunWorker();return}this.log.DEBUG?.(`Data out updated`,n?.instance)}shouldHandleStateChange(e){let{useSharedState:t,handleStateChange:n,handleSharedStateChange:r}=this.data;return e===`local`?!!(t?r?.includes(`local`):n):!!(t&&r?.includes(`remote`))}tryRunWorker(){if(N.isBusy(this.thread)){this.log.DEBUG?.(`Skip change processing. Worker thread is busy`);return}let e=this.state.changes.shift();e!=null&&(this.log.DEBUG?.(`Notify change listener worker thread about change to process`,e),N.start(this.thread,e))}runStep(){let{useSharedState:e}=this.data,t=this.shouldHandleStateChange(`local`),n=this.shouldHandleStateChange(`remote`),r=t||n;this.triggers.local({name:F.stateChanged},this.onLocalStateChange),e&&this.triggers.once({name:this.remoteChangeEventName,topic:this.thread.config.flowId},this.onRemoteStateChange),r&&this.triggers.hook({name:`end`,thread:N.getThreadId(this.thread.step.id)},this.onWorkerThreadEnd),this.triggers.otherwise(this.initialize)}initialize(){this.log.DEBUG?.(`Initializing ChangeListener thread...`)}async onLocalStateChange(e){this.log.DEBUG?.(`State has been changed in current flow`,e),await this.handleChange(`local`)}async onRemoteStateChange(e){this.log.DEBUG?.(`State has been changed in remote flow`,e),await this.handleChange(`remote`)}onWorkerThreadEnd(e){let{result:t}=e.params.thread;if(this.log.DEBUG?.(`ChangeListenerWorker thread finished processing change`,t),t instanceof Error)throw h(t,{unknownMessage:`ChangeListenerWorker thread ended with an error`});this.tryRunWorker()}};O([_,D(`design:type`,Function),D(`design:paramtypes`,[]),D(`design:returntype`,void 0)],I.prototype,`runStep`,null),O([_,D(`design:type`,Function),D(`design:paramtypes`,[]),D(`design:returntype`,void 0)],I.prototype,`initialize`,null),O([_,D(`design:type`,Function),D(`design:paramtypes`,[Object]),D(`design:returntype`,Promise)],I.prototype,`onLocalStateChange`,null),O([_,D(`design:type`,Function),D(`design:paramtypes`,[Object]),D(`design:returntype`,Promise)],I.prototype,`onRemoteStateChange`,null),O([_,D(`design:type`,Function),D(`design:paramtypes`,[Object]),D(`design:returntype`,void 0)],I.prototype,`onWorkerThreadEnd`,null);const L=e(import.meta.url);async function R(e){if(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e))throw Error(`Invalid minimum version format: ${e}`);let t=L.resolve(`@onereach/flow-sdk/package.json`);if(!t)throw Error(`Could not find package.json for @onereach/flow-sdk`);let n=await d(t,`utf8`),{version:r}=JSON.parse(n),{groups:i}=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)/.exec(r)||{};if(!i)throw Error(`Invalid Flow SDK version format: ${r}`);let a=Math.trunc(Number(i.major??`0`)),o=Math.trunc(Number(i.minor??`0`)),s=Math.trunc(Number(i.patch??`0`));if(a==null||o==null||s==null||Number.isNaN(a)||Number.isNaN(o)||Number.isNaN(s))throw Error(`Invalid version format: ${r}`);let[c,l,u]=e.split(`.`).map(e=>Math.trunc(Number(e)));if(c==null||l==null||u==null||Number.isNaN(c)||Number.isNaN(l)||Number.isNaN(u))throw Error(`Invalid minimum version format: ${e}`);if(a<c||a===c&&o<l||a===c&&o===l&&s<u)throw Error(`Flow SDK version '${r}' is lower than required minimum version '${e}' for the step`)}var z=class extends k{validateMergeFieldType(){if(this.dataOut==null||this.getMergeField(this.dataOut).type===`thread`)throw new p(`Merge-field type can not be "Thread" for this step`,{code:f.VALIDATION})}get stateMachine(){return new r(this.thread,{cache:this.data._testSettings?.cache,instanceTtl:this.instanceTtl}).stateMachine}get instanceTtl(){let{stateTtl:e}=this.data;return e?.input?a(e.input,e.outputMode):void 0}async runStep(){await R(`8.0.72`),this.validateMergeFieldType(),this.step.dataOut&&await I.start(this.thread);let{stateId:e,stateTemplateId:t,handleMissingTemplate:r}=this.data,i=await this.stateMachine.load({id:e});if(i==null)try{i=await this.stateMachine.create({id:e,template:{id:t}})}catch(e){if(r&&e instanceof n){this.exitStep(`not found`);return}throw e}this.exitStep(`next`,i.instance)}};O([w,D(`design:type`,Function),D(`design:paramtypes`,[]),D(`design:returntype`,Promise)],z.prototype,`runStep`,null),t();const B={[I.class]:I,[N.class]:N};export{I as ChangeListener,N as ChangeListenerWorker,z as InitializeStateMachineStep,z as step,P as changeListenerClassId,F as changeListenerEvents,j as changeListenerWorkerClassId,M as changeListenerWorkerExits,B as states};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["defaultOptions"],"sources":["../src/errors/step-error.ts","../src/errors/error-filter.ts","../src/utils/create-method-decorator.ts","../src/decorators/background-thread-error-filter.ts","../src/utils/thread-utilities.ts","../src/decorators/error-filter.ts","../src/schemas/data-in.ts","../src/threads/base/base.ts","../src/threads/base/constants.ts","../src/threads/change-listener/worker/constants.ts","../src/threads/change-listener/worker/change-listener-worker.ts","../src/threads/change-listener/listener/constants.ts","../src/threads/change-listener/listener/change-listener.ts","../src/utils/validate-flow-sdk-version.ts","../src/threads/main/step.ts","../src/index.ts"],"sourcesContent":["import { BasicError } from '@onereach/flow-sdk/errors/base.js';\n\nexport const ErrorCode = {\n UNKNOWN: 'UNKNOWN',\n STEP_LOGIC_ISSUE: 'STEP_LOGIC_ISSUE',\n TIMEOUT: 'TIMEOUT',\n VALIDATION: 'VALIDATION',\n SERVER_ERROR: 'SERVER_ERROR',\n UNSUPPORTED: 'UNSUPPORTED',\n} as const;\n\nexport class InitializeStateMachineStepError extends BasicError<{\n code: keyof typeof ErrorCode;\n data?: unknown;\n}> {}\n\nexport class AbortRequestError extends BasicError {}\n","import { TimeoutError } from '@onereach/flow-sdk/errors/timeout.js';\nimport * as z from 'zod/mini';\n\nimport { InitializeStateMachineStepError, ErrorCode } from './step-error.ts';\n\n// eslint-disable-next-line unicorn/no-top-level-side-effects\nz.config(z.locales.en());\n\nconst defaultPreserveErrors = [InitializeStateMachineStepError, TimeoutError] as const;\nexport function errorFilter<P extends readonly AnyErrorClass[] = typeof defaultPreserveErrors>(\n error: unknown,\n options: ErrorFilterOptions<P> = {},\n): InstancesOf<P> | InitializeStateMachineStepError | TimeoutError {\n const {\n preserveErrors = defaultPreserveErrors,\n unknownMessage = 'Unknown error',\n unknownCode = ErrorCode.UNKNOWN,\n } = options;\n\n // if error is CreateChatCompletionStepError or TimeoutError, return it directly\n if (preserveErrors?.some((ErrorClass) => error instanceof ErrorClass)) {\n return error as InstancesOf<P>;\n }\n\n // validation errors\n if (error instanceof z.core.$ZodError) {\n return new InitializeStateMachineStepError(z.prettifyError(error), error, {\n code: ErrorCode.VALIDATION,\n });\n }\n\n // if error is a string assume it's an error message\n if (typeof error === 'string') {\n return new InitializeStateMachineStepError(error, {\n code: ErrorCode.UNKNOWN,\n });\n }\n\n if (error instanceof Error) {\n // timeout errors\n if (error.message.includes('Request timed out')) {\n return new TimeoutError('Timeout', error, { code: ErrorCode.TIMEOUT });\n }\n\n // TODO: fix interpreting of this kind of errors\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n const responseErrorMessage: string | undefined = (error as unknown as any)?.response?.data?.error?.message;\n if (responseErrorMessage != undefined) {\n return new InitializeStateMachineStepError(responseErrorMessage, error, {\n code: ErrorCode.SERVER_ERROR,\n });\n }\n\n return new InitializeStateMachineStepError(unknownMessage, error, {\n code: unknownCode,\n });\n }\n\n // catch all for unknown errors\n return new InitializeStateMachineStepError(unknownMessage, {\n code: unknownCode,\n data: error,\n });\n}\n\nexport type ErrorFilterOptions<P extends readonly AnyErrorClass[]> = {\n /**\n Array of error classes that should not be wrapped\n */\n preserveErrors?: P;\n /**\n Error message to use when message is unknown\n */\n unknownMessage?: string;\n /**\n Error code to use when message is unknown\n */\n unknownCode?: keyof typeof ErrorCode;\n};\n\n/**\nAny Error class\n*/\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyErrorClass<E extends Error = Error> = new (...arguments_: any[]) => E;\n\n/**\nTurn a tuple/array of constructors into a union of their instance types.\n*/\nexport type InstancesOf<Ctors extends readonly AnyErrorClass[]> =\n Ctors[number] extends AnyErrorClass<infer I> ? I : never;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Creates a method decorator that can be used with or without options.\n * @param apply - Function that applies the decorator logic with given options.\n * @param defaultOptions - Default options to use if none are provided.\n */\nexport function createMethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction>(\n apply: (\n options: A,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => T | TypedPropertyDescriptor<T> | void,\n defaultOptions: A,\n): MethodDecoratorWithOptionalArguments<A, T> {\n function runApply(\n options: A,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ): TypedPropertyDescriptor<T> | void {\n const maybe = apply(options, target, propertyKey, descriptor);\n\n // If the decorator factory returned a wrapped function, assign it to the descriptor here\n if (typeof maybe === 'function') {\n const originalMethod = descriptor.value;\n const wrappedMethod = maybe as typeof originalMethod;\n\n if (originalMethod?.name != undefined) {\n try {\n Object.defineProperty(wrappedMethod, 'name', { value: originalMethod.name });\n } catch {\n // ignore if name is non-configurable\n }\n }\n\n descriptor.value = wrappedMethod;\n return descriptor;\n }\n\n // If a descriptor was returned or decorator mutated descriptor in-place, use that\n return maybe ?? descriptor;\n }\n\n return function decoratorOrFactory(\n argument0?: object | A,\n argument1?: string | symbol,\n argument2?: TypedPropertyDescriptor<T>,\n ): any {\n if (\n argument0 !== null &&\n argument2 !== null &&\n typeof argument0 === 'object' &&\n typeof argument2 === 'object' &&\n (typeof argument1 === 'string' || typeof argument1 === 'symbol')\n ) {\n // Called as plain decorator: @Decorator\n return runApply(defaultOptions, argument0, argument1, argument2);\n }\n\n // Called as decorator factory: @Decorator(options)\n const options = (argument0 as A) ?? defaultOptions;\n return (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => {\n return runApply(options, target, propertyKey, descriptor);\n };\n };\n}\n\nexport type AnyFunction = (...arguments_: any[]) => any;\n\nexport type MethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction> =\n // Plain method decorator (three arguments)\n ((\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => TypedPropertyDescriptor<T> | void) &\n // Decorator factory (optional options argument)\n ((options?: A) => MethodDecorator);\n","/* eslint-disable unicorn/prefer-await */\n\nimport type { Step } from '@onereach/flow-sdk/step.js';\nimport { ACTION } from '@onereach/flow-sdk/types/index.js';\n\nimport { errorFilter } from '../errors/error-filter.ts';\nimport { createMethodDecoratorWithOptionalArguments } from '../utils/create-method-decorator.ts';\n\nconst defaultOptions: BackgroundThreadErrorFilterOptions = { allowHandleError: false, useErrorFilter: true };\n\n/**\n * Since errors in hooks are fatal and can't be processed this decorator allows to wrap hook handler\n * and manage errors by ending a thread with the error (preventing sending error to `error` exit)\n * @param options.allowHandleError - Default `false`. If `false` in case of error will end thread with error as result, if `true` will allow to handle error via 'error' exit\n * @param options.useErrorFilter - Default `true`. If `true` every error wild be processed with `errorFilter` utility function\n */\nexport const BackgroundThreadErrorFilter = createMethodDecoratorWithOptionalArguments(\n (options, _target, propertyKey, descriptor) => {\n const originalMethod = descriptor.value;\n if (!originalMethod || typeof originalMethod !== 'function') return;\n\n return function (this: Step, ...arguments_: Parameters<typeof originalMethod>): ReturnType<typeof originalMethod> {\n try {\n const result: unknown = originalMethod.apply(this, arguments_);\n\n if (result instanceof Promise) {\n return result.catch((error) => errorHandler.call(this, options, error, propertyKey));\n }\n\n return result;\n } catch (error) {\n return errorHandler.call(this, options, error, propertyKey) as ReturnType<typeof originalMethod>;\n }\n } as typeof originalMethod;\n },\n defaultOptions,\n);\n\nfunction errorHandler(\n this: Step,\n options: BackgroundThreadErrorFilterOptions,\n error: unknown,\n propertyKey: string | symbol,\n): void {\n const methodName = propertyKey.toString();\n this.log.DEBUG?.(`Error in method '${methodName}'`, error);\n const filteredError = options.useErrorFilter ? errorFilter(error) : error;\n\n if (filteredError instanceof Error) {\n if (options.allowHandleError) {\n // Send it to the 'error' exit and stop here\n this.thread.enqueue({ name: ACTION.error, error: filteredError });\n return;\n }\n // End the thread with the error and stop here\n this.end(filteredError);\n return;\n }\n\n // Only throw if it's not an Error instance and you truly want to bubble it\n throw filteredError;\n}\n\nexport type BackgroundThreadErrorFilterOptions = {\n allowHandleError?: boolean;\n useErrorFilter?: boolean;\n};\n","import { ACTION } from '@onereach/flow-sdk/types/index.js';\nimport type { CONFIG, IThread, IThreadId, IThreadOptions, RESULT } from '@onereach/flow-sdk/types/index.js';\n\n/**\n * Runs a new thread or reuses an existing one (if it ended).\n * @param thread The step to run the thread for.\n * @throws Error if the thread is not ended or if the state is not provided.\n */\nexport async function runChildThread<ThreadConfig extends CONFIG & ManagedThreadConfig, StepConfig extends CONFIG>(\n thread: IThread<StepConfig>,\n { id, state, local, ...options }: IThreadOptions<ThreadConfig>,\n { force }: { force?: boolean } = {},\n): Promise<RESULT<ThreadConfig>> {\n const threadToRun = thread.process.getThread<ThreadConfig>(id);\n thread.log.DEBUG?.(`runThread: thread with id '${id}'`, options);\n\n if (threadToRun == undefined) {\n // create thread\n return await thread.thread.runThread<ThreadConfig>({\n ...options,\n id,\n state,\n local: {\n ...local,\n parent: thread.thread.id,\n active: true,\n },\n });\n }\n\n if (!force && !threadToRun.ended && threadToRun.local.active)\n throw new Error(`Thread with id '${id}' has not ended yet, cannot start it again`);\n if (state == undefined) throw new Error(`Thread with id '${id}' must have a state to run`);\n\n // reuse existing thread\n threadToRun.local.active = true;\n return await threadToRun.enqueueAndRun({\n name: ACTION.goto,\n state: {\n ...state,\n active: true,\n },\n });\n}\n\nexport function isThreadBusy<StepConfig extends CONFIG, ThreadConfig extends CONFIG & ManagedThreadConfig>(\n thread: IThread<StepConfig>,\n threadId: IThreadId,\n): boolean {\n const threadToCheck = thread.process.getThread<ThreadConfig>(threadId);\n return threadToCheck != undefined && threadToCheck.local.active && !threadToCheck.ended;\n}\n\nexport function listChildThreads<StepConfig extends CONFIG, ChildThreadConfig extends CONFIG & ManagedThreadConfig>(\n thread: IThread<StepConfig>,\n parentThreadId: IThreadId = thread.id,\n): IThread<ChildThreadConfig>[] {\n const childThreads = [];\n for (const threadId in thread.process.threads) {\n const item = thread.process.threads[threadId]! as unknown as IThread<ChildThreadConfig>;\n if (item?.local.parent === parentThreadId) childThreads.push(item);\n }\n return childThreads;\n}\n\nexport async function stopThread<ThreadConfig extends CONFIG & ManagedThreadConfig, StepConfig extends CONFIG>(\n thread: IThread<StepConfig>,\n id: IThreadId,\n { result, stopChildThreads }: { result?: RESULT<ThreadConfig>; stopChildThreads?: boolean } = {},\n): Promise<void> {\n const threadToStop = thread.process.getThread<ThreadConfig>(id);\n thread.log.DEBUG?.(`stopThread: thread with id '${id}'`);\n\n if (!threadToStop) return;\n\n if (stopChildThreads) await endChildThreads(threadToStop, result);\n\n if (!threadToStop.local.active) return;\n\n threadToStop.local.active = false;\n if (threadToStop.ended) return;\n\n await threadToStop.enqueueAndRun({ name: ACTION.ending, result });\n}\n\nexport async function endChildThreads<ThreadConfig extends CONFIG, StepConfig extends CONFIG>(\n thread: IThread<StepConfig>,\n result?: RESULT<ThreadConfig>,\n options: { throw?: boolean } = {},\n): Promise<PromiseSettledResult<void>[]> {\n const childThreads = listChildThreads(thread);\n const stopTasks = childThreads.map(\n async (child) => await stopThread(thread, child.id, { stopChildThreads: true, result }),\n );\n const stopResults = await Promise.allSettled(stopTasks);\n\n const isThrowError = options.throw ?? true;\n if (isThrowError) {\n const failedTask = stopResults.find((task) => task.status === 'rejected');\n if (failedTask) throw failedTask.reason;\n }\n\n return stopResults;\n}\n\nexport type ManagedThreadLocal = {\n active: boolean;\n parent: IThreadId;\n};\n\nexport type ManagedThreadConfig = {\n local: ManagedThreadLocal;\n};\n","/* eslint-disable unicorn/prefer-await */\n\nimport type { Step } from '@onereach/flow-sdk/step.js';\n\nimport { errorFilter } from '../errors/error-filter.ts';\nimport { createMethodDecoratorWithOptionalArguments } from '../utils/create-method-decorator.ts';\n\nconst defaultOptions = {};\n\n/**\n * Will wrap method with `errorFilter` for every error.\n */\nexport const ErrorFilter = createMethodDecoratorWithOptionalArguments((_options, _target, propertyKey, descriptor) => {\n const originalMethod = descriptor.value;\n\n if (!originalMethod || typeof originalMethod !== 'function') return;\n\n return function (this: Step, ...arguments_: Parameters<typeof originalMethod>): ReturnType<typeof originalMethod> {\n try {\n const result: unknown = originalMethod.apply(this, arguments_);\n\n if (result instanceof Promise) {\n return result.catch((error: unknown) => {\n const methodName = propertyKey.toString();\n this.log.DEBUG?.(`Error in method '${methodName}'`, error);\n throw errorFilter(error);\n }) as ReturnType<typeof originalMethod>;\n }\n\n return result;\n } catch (error) {\n const methodName = propertyKey.toString();\n this.log.DEBUG?.(`Error in method '${methodName}'`, error);\n throw errorFilter(error);\n }\n };\n}, defaultOptions);\n","/* eslint-disable unicorn/max-nested-calls */\nimport type { ICacheFacade } from '@onereach/flow-sdk/types/index.js';\nimport * as z from 'zod/mini';\n\n// eslint-disable-next-line unicorn/no-top-level-side-effects\nz.config(z.locales.en());\n\n// string that prevents\nconst stringNoUndefinedSchema = z.string().check(\n z.trim(),\n z.refine((value) => !['undefined', 'null'].includes(value), {\n error: 'Unexpected undefined or null merge-field value',\n }),\n);\n\nexport const dataInSchema = z.object({\n stateTemplateId: stringNoUndefinedSchema.check(z.minLength(1), z.maxLength(64)),\n handleMissingTemplate: z.optional(z.boolean()),\n\n stateId: stringNoUndefinedSchema.check(z.minLength(1), z.maxLength(64)),\n stateTtl: z.optional(\n z.object({\n input: stringNoUndefinedSchema,\n outputMode: z.enum(['ms', 's', 'm', 'h', 'd']),\n }),\n ),\n customizeInitialValue: z.optional(z.boolean()),\n\n useSharedState: z.optional(z.boolean()),\n handleStateChange: z.optional(z.boolean()),\n handleSharedStateChange: z.optional(z.array(z.enum(['local', 'remote']))),\n\n processError: z.boolean(),\n processTimeout: z.boolean(),\n timeoutDuration: stringNoUndefinedSchema.check(z.trim(), z.minLength(1)),\n\n // for integration tests\n _testSettings: z.optional(\n z.object({\n cache: z.optional(z.custom<ICacheFacade>()),\n }),\n ),\n});\n\nexport type DataIn = z.infer<typeof dataInSchema>;\n\n// /**\n// * Convert empty string to undefined before running schema validation\n// * @param schema schema to validate against\n// * @param defaultValue optional default value\n// */\n// function optionalStringValue<T extends z.core.SomeType>(schema: T) {\n// return z.optional(\n// z.pipe(\n// z.union([z.undefined(), z.literal(''), schema]),\n// z.transform((value) => (value === '' ? undefined : value)),\n// ),\n// );\n// }\n","import { Step } from '@onereach/flow-sdk/step.js';\n\nimport { ErrorFilter } from '../../decorators/error-filter.ts';\nimport { dataInSchema } from '../../schemas/data-in.ts';\n\nimport type { BaseConfig } from './types.ts';\n\n// TODO: convert it into class decorator\nexport class BaseStep<T extends BaseConfig> extends Step<T> {\n @ErrorFilter\n public async resolveDataIn() {\n const dataIn = await super.resolveDataIn();\n return dataInSchema.parse(dataIn);\n }\n}\n","export const baseClassIdPrefix = 'sm_mgr';\n","export const changeListenerWorkerClassId = 'chg_wrk';\n\nexport const changeListenerWorkerExits = {\n local: 'local change',\n remote: 'remote change',\n} as const;\n","import type { IStepId, IThread, IThreadId } from '@onereach/flow-sdk/types/index.js';\n\nimport { ErrorFilter } from '../../../decorators/error-filter.ts';\nimport { InitializeStateMachineStepError, ErrorCode } from '../../../errors/step-error.ts';\nimport { isThreadBusy, runChildThread } from '../../../utils/thread-utilities.ts';\nimport { BaseStep } from '../../base/base.ts';\nimport { baseClassIdPrefix } from '../../base/constants.ts';\nimport type { ChangeListenerChange, ChangeListenerConfig } from '../listener/types.ts';\n\nimport { changeListenerWorkerClassId, changeListenerWorkerExits } from './constants.ts';\nimport type { ChangeListenerWorkerConfig } from './types.ts';\n\nexport class ChangeListenerWorker extends BaseStep<ChangeListenerWorkerConfig> {\n public static readonly class = changeListenerWorkerClassId;\n\n public static async start(thread: IThread<ChangeListenerConfig>, change: ChangeListenerChange): Promise<void> {\n await runChildThread<ChangeListenerWorkerConfig, ChangeListenerConfig>(thread, {\n id: this.getThreadId(thread.step.id),\n state: {\n step: thread.step.id,\n class: this.class,\n\n change,\n },\n });\n }\n\n public static isBusy(thread: IThread<ChangeListenerConfig>): boolean {\n return isThreadBusy<ChangeListenerConfig, ChangeListenerWorkerConfig>(thread, this.getThreadId(thread.step.id));\n }\n\n public static getThreadId(stepId: IStepId): IThreadId {\n return `${baseClassIdPrefix}_${this.class}_${stepId}`;\n }\n\n // ----------------------------------------------\n\n @ErrorFilter\n public runStep(): void {\n if (this.state.change == undefined) {\n throw new InitializeStateMachineStepError(\n 'Change listener worker thread state must contain an instance to process',\n {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n },\n );\n }\n\n const { change } = this.state;\n this.log.DEBUG?.('Executing change listener worker thread', change);\n this.exitStep(changeListenerWorkerExits[change.type], change.change.instance);\n }\n}\n","export const changeListenerClassId = 'cng_lnr';\n\nexport const changeListenerEvents = {\n stateChanged: 'st_cgd',\n} as const;\n","/* eslint-disable @typescript-eslint/unbound-method */\n\nimport type { CONFIG, IActionEvent, IStepId, IThread, IThreadId } from '@onereach/flow-sdk/types/index.js';\nimport {\n InitializeStateMachineContext,\n StateMachineService,\n StateMachineThreadService,\n} from '@onereach/state-machine-step-service';\nimport { setImmediate } from 'node:timers/promises';\nimport timestring from 'timestring';\n\nimport { BackgroundThreadErrorFilter } from '../../../decorators/background-thread-error-filter.ts';\nimport { errorFilter } from '../../../errors/error-filter.ts';\nimport { ErrorCode, InitializeStateMachineStepError } from '../../../errors/step-error.ts';\nimport { runChildThread, stopThread } from '../../../utils/thread-utilities.ts';\nimport { BaseStep } from '../../base/base.ts';\nimport { baseClassIdPrefix } from '../../base/constants.ts';\nimport { InitializeStateMachineConfig } from '../../main/types.ts';\nimport { ChangeListenerWorker } from '../worker/change-listener-worker.ts';\nimport { ChangeListenerWorkerConfig } from '../worker/types.ts';\n\nimport { changeListenerClassId, changeListenerEvents } from './constants.ts';\nimport type {\n ChangeListenerConfig,\n ChangeListenerLocalChangeEvent,\n ChangeListenerRemoteChangeEvent,\n ChangeListenerRemoteChangeEventName,\n} from './types.ts';\n\nexport class ChangeListener extends BaseStep<ChangeListenerConfig> {\n public static readonly class = changeListenerClassId;\n\n public static async start(thread: IThread<InitializeStateMachineConfig>): Promise<void> {\n await runChildThread<ChangeListenerConfig, InitializeStateMachineConfig>(\n thread,\n {\n id: this.getThreadId(thread.step.id),\n state: {\n step: thread.step.id,\n class: this.class,\n\n changes: [],\n },\n background: true,\n },\n { force: true },\n );\n }\n\n public static async stop<TConfig extends CONFIG>(thread: IThread<TConfig>): Promise<void> {\n await stopThread(thread, this.getThreadId(thread.step.id));\n }\n\n public static getThreadId(stepId: IStepId): IThreadId {\n return `${baseClassIdPrefix}_${this.class}_${stepId}`;\n }\n\n // ---------------------------------------\n\n private get stateMachine(): StateMachineService<InitializeStateMachineContext> {\n const service = new StateMachineThreadService<ChangeListenerConfig, InitializeStateMachineContext>(this.thread, {\n cache: this.data._testSettings?.cache,\n instanceTtl: this.instanceTtl,\n });\n return service.stateMachine;\n }\n\n private get instanceTtl(): number | undefined {\n const { stateTtl } = this.data;\n return stateTtl?.input ? timestring(stateTtl.input, stateTtl.outputMode) : undefined;\n }\n\n private get remoteChangeEventName(): ChangeListenerRemoteChangeEventName {\n const { stateTemplateId, stateId } = this.data;\n\n return `sm/${stateTemplateId}/${stateId}`;\n }\n\n private async handleChange(changeType: 'local' | 'remote'): Promise<void> {\n const { stateId } = this.data;\n const updated = await this.stateMachine.load({ id: stateId });\n\n // TODO: handle state deletion\n if (updated == undefined) return;\n\n // TODO: check if there was an actual change, only then update data out and run worker thread\n const currentDataOut = await this.getDataOut();\n\n if (currentDataOut == undefined)\n throw new InitializeStateMachineStepError('Data out is not set', {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n });\n\n // skip data out update if the sequence is the same\n if (updated.instance.sequence === currentDataOut.sequence) {\n this.log.WARN?.('Skip change processing. Sequence is the same', { sequence: updated.instance.sequence });\n return;\n }\n\n await this.setDataOut(updated?.instance);\n\n if (this.shouldHandleStateChange(changeType)) {\n this.state.changes.push({\n change: updated,\n type: changeType,\n });\n // release the event loop to unblock the thread\n await setImmediate();\n this.tryRunWorker();\n return;\n }\n\n this.log.DEBUG?.('Data out updated', updated?.instance);\n }\n\n private shouldHandleStateChange(type: 'local' | 'remote'): boolean {\n const { useSharedState, handleStateChange, handleSharedStateChange } = this.data;\n\n return type === 'local'\n ? Boolean(useSharedState ? handleSharedStateChange?.includes('local') : handleStateChange)\n : Boolean(useSharedState && handleSharedStateChange?.includes('remote'));\n }\n\n /**\n * Processes the next change in the listener thread's queue.\n * If the worker thread is busy, it skips processing.\n * If the event is the termination marker, it notifies the end of the controller thread.\n * If the event is ready for processing, it starts the worker thread to handle it.\n */\n private tryRunWorker(): void {\n // skip if worker thread is busy\n if (ChangeListenerWorker.isBusy(this.thread)) {\n this.log.DEBUG?.('Skip change processing. Worker thread is busy');\n return;\n }\n\n const change = this.state.changes.shift();\n if (change == undefined) return;\n\n this.log.DEBUG?.('Notify change listener worker thread about change to process', change);\n\n void ChangeListenerWorker.start(this.thread, change);\n }\n\n @BackgroundThreadErrorFilter\n public runStep(): void {\n const { useSharedState } = this.data;\n const shouldHandleLocalChanges = this.shouldHandleStateChange('local');\n const shouldHandleRemoteChanges = this.shouldHandleStateChange('remote');\n const shouldHandleChanges = shouldHandleLocalChanges || shouldHandleRemoteChanges;\n\n this.triggers.local({ name: changeListenerEvents.stateChanged }, this.onLocalStateChange);\n if (useSharedState) {\n this.triggers.once(\n { name: this.remoteChangeEventName, topic: this.thread.config.flowId },\n this.onRemoteStateChange,\n );\n }\n if (shouldHandleChanges) {\n this.triggers.hook<ChangeListenerWorkerConfig, 'end'>(\n { name: 'end', thread: ChangeListenerWorker.getThreadId(this.thread.step.id) },\n this.onWorkerThreadEnd,\n );\n }\n this.triggers.otherwise(this.initialize);\n }\n\n @BackgroundThreadErrorFilter\n public initialize(): void {\n this.log.DEBUG?.('Initializing ChangeListener thread...');\n }\n\n @BackgroundThreadErrorFilter\n public async onLocalStateChange(event: ChangeListenerLocalChangeEvent): Promise<void> {\n this.log.DEBUG?.(`State has been changed in current flow`, event);\n\n await this.handleChange('local');\n }\n\n @BackgroundThreadErrorFilter\n public async onRemoteStateChange(event: ChangeListenerRemoteChangeEvent): Promise<void> {\n this.log.DEBUG?.(`State has been changed in remote flow`, event);\n\n await this.handleChange('remote');\n }\n\n /**\n * Handler of the worker thread end event.\n */\n @BackgroundThreadErrorFilter\n public onWorkerThreadEnd(event: IActionEvent<ChangeListenerWorkerConfig, 'end'>): void {\n const { result } = event.params.thread;\n\n this.log.DEBUG?.('ChangeListenerWorker thread finished processing change', result);\n\n if (result instanceof Error) {\n const resultError = errorFilter(result, {\n unknownMessage: 'ChangeListenerWorker thread ended with an error',\n });\n throw resultError;\n }\n\n // check if there are more tool calls or content chunks to process\n this.tryRunWorker();\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\n\nconst require = createRequire(import.meta.url);\n\nexport async function validateFlowSdkVersion(minVersion: string): Promise<void> {\n if (typeof minVersion !== 'string' || !/^\\d+\\.\\d+\\.\\d+$/.test(minVersion)) {\n throw new Error(`Invalid minimum version format: ${minVersion}`);\n }\n\n const packageJsonPath = require.resolve('@onereach/flow-sdk/package.json');\n if (!packageJsonPath) {\n throw new Error(`Could not find package.json for @onereach/flow-sdk`);\n }\n // Read the package.json file to get the version\n const packageJsonContent = await readFile(packageJsonPath, 'utf8');\n\n const { version } = JSON.parse(packageJsonContent) as { version: string };\n const { groups } = /^(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)/.exec(version) || {};\n\n if (!groups) throw new Error(`Invalid Flow SDK version format: ${version}`);\n\n const major = Math.trunc(Number(groups.major ?? '0'));\n const minor = Math.trunc(Number(groups.minor ?? '0'));\n const patch = Math.trunc(Number(groups.patch ?? '0'));\n\n if (\n major == undefined ||\n minor == undefined ||\n patch == undefined ||\n Number.isNaN(major) ||\n Number.isNaN(minor) ||\n Number.isNaN(patch)\n ) {\n throw new Error(`Invalid version format: ${version}`);\n }\n\n const [minMajor, minMinor, minPatch] = minVersion.split('.').map((x) => Math.trunc(Number(x)));\n\n if (\n minMajor == undefined ||\n minMinor == undefined ||\n minPatch == undefined ||\n Number.isNaN(minMajor) ||\n Number.isNaN(minMinor) ||\n Number.isNaN(minPatch)\n ) {\n throw new Error(`Invalid minimum version format: ${minVersion}`);\n }\n\n if (\n major < minMajor ||\n (major === minMajor && minor < minMinor) ||\n (major === minMajor && minor === minMinor && patch < minPatch)\n ) {\n throw new Error(\n `Flow SDK version '${version}' is lower than required minimum version '${minVersion}' for the step`,\n );\n }\n}\n","import { StateMachineThreadService, NotFoundError } from '@onereach/state-machine-step-service';\nimport type { InitializeStateMachineContext, StateMachineService } from '@onereach/state-machine-step-service';\nimport timestring from 'timestring';\n\nimport { ErrorFilter } from '../../decorators/error-filter.ts';\nimport { ErrorCode, InitializeStateMachineStepError } from '../../errors/step-error.ts';\nimport { validateFlowSdkVersion } from '../../utils/validate-flow-sdk-version.ts';\nimport { BaseStep } from '../base/base.ts';\nimport { ChangeListener } from '../change-listener/listener/change-listener.ts';\n\nimport type { InitializeStateMachineConfig } from './types.ts';\n\nconst MINIMAL_FLOW_SDK_VERSION = '8.0.72';\n\nexport class InitializeStateMachineStep extends BaseStep<InitializeStateMachineConfig> {\n private validateMergeFieldType(): void {\n if (this.dataOut == undefined || this.getMergeField(this.dataOut).type === 'thread') {\n throw new InitializeStateMachineStepError('Merge-field type can not be \"Thread\" for this step', {\n code: ErrorCode.VALIDATION,\n });\n }\n }\n\n private get stateMachine(): StateMachineService<InitializeStateMachineContext> {\n const service = new StateMachineThreadService<InitializeStateMachineConfig, InitializeStateMachineContext>(\n this.thread,\n {\n cache: this.data._testSettings?.cache,\n instanceTtl: this.instanceTtl,\n },\n );\n return service.stateMachine;\n }\n\n private get instanceTtl(): number | undefined {\n const { stateTtl } = this.data;\n return stateTtl?.input ? timestring(stateTtl.input, stateTtl.outputMode) : undefined;\n }\n\n @ErrorFilter\n public async runStep(): Promise<void> {\n await validateFlowSdkVersion(MINIMAL_FLOW_SDK_VERSION);\n this.validateMergeFieldType();\n\n if (this.step.dataOut) await ChangeListener.start(this.thread);\n\n const { stateId, stateTemplateId, handleMissingTemplate } = this.data;\n let snapshot = await this.stateMachine.load({ id: stateId });\n\n if (snapshot == undefined) {\n // TODO: run logic with overriding initial state value\n try {\n snapshot = await this.stateMachine.create({\n id: stateId,\n template: {\n id: stateTemplateId,\n // version: 'xxx' // TODO: add support for version of state machine template\n },\n });\n } catch (error) {\n if (handleMissingTemplate && error instanceof NotFoundError) {\n this.exitStep('not found');\n return;\n }\n\n throw error;\n }\n }\n\n this.exitStep('next', snapshot.instance);\n }\n}\n","import { install } from 'source-map-support';\n\nimport { ChangeListener } from './threads/change-listener/listener/change-listener.ts';\nimport { ChangeListenerWorker } from './threads/change-listener/worker/change-listener-worker.ts';\n\n// enable source map support for better error stack traces\n// eslint-disable-next-line unicorn/no-top-level-side-effects\ninstall();\n\nexport const states = {\n [ChangeListener.class]: ChangeListener,\n [ChangeListenerWorker.class]: ChangeListenerWorker,\n};\n\nexport { InitializeStateMachineStep as step, InitializeStateMachineStep } from './threads/main/step.ts';\n\nexport { ChangeListener } from './threads/change-listener/listener/change-listener.ts';\nexport { ChangeListenerWorker } from './threads/change-listener/worker/change-listener-worker.ts';\nexport * from './threads/change-listener/listener/constants.ts';\nexport * from './threads/change-listener/worker/constants.ts';\n\nexport type * from './types.ts';\n"],"mappings":"kkBAEA,MAAa,EAAY,CACvB,QAAS,UACT,iBAAkB,mBAClB,QAAS,UACT,WAAY,aACZ,aAAc,eACd,YAAa,aACf,EAEA,IAAa,EAAb,cAAqD,CAGlD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AI,GAAY,KAEd,GAAI,CACF,EAAW,MAAM,KAAK,aAAa,OAAO,CACxC,GAAI,EACJ,SAAU,CACR,GAAI,CAEN,CACF,CAAC,CACH,OAAS,EAAO,CACd,GAAI,GAAyB,aAAiB,EAAe,CAC3D,KAAK,SAAS,WAAW,EACzB,MACF,CAEA,MAAM,CACR,CAGF,KAAK,SAAS,OAAQ,EAAS,QAAQ,CACzC,CACF,KAhCG,kHChCH,EAAQ,EAER,MAAa,EAAS,EACnB,EAAe,OAAQ,GACvB,EAAqB,OAAQ,CAChC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@onereach/step-initialize-state-manager",
|
|
3
|
+
"version": "1.0.0-framework.11",
|
|
4
|
+
"description": "Logic for Initializing State Manager step",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./dist/index.mjs",
|
|
8
|
+
"./package.json": "./package.json"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"!dist/metafile*.json"
|
|
13
|
+
],
|
|
14
|
+
"keywords": [
|
|
15
|
+
"onereach",
|
|
16
|
+
"toolkit",
|
|
17
|
+
"step"
|
|
18
|
+
],
|
|
19
|
+
"author": "OneReach Development Team <dev.team@onereach.ai>",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@arethetypeswrong/core": "^0.18.5",
|
|
26
|
+
"@onereach/flow-sdk": "v9.0.0-monosplit.5",
|
|
27
|
+
"@onereach/flow-sdk-mocks": "v9.0.0-monosplit.5",
|
|
28
|
+
"@onereach/orb-promises": "^8.1.3",
|
|
29
|
+
"@onereach/orb-storage": "^8.1.3",
|
|
30
|
+
"@onereach/step-execute-state-machine-function": "1.0.0-framework.11",
|
|
31
|
+
"@types/source-map-support": "^0.5.10",
|
|
32
|
+
"@types/timestring": "^7.0.0",
|
|
33
|
+
"publint": "^0.3.24",
|
|
34
|
+
"rollup-plugin-visualizer": "^7.1.1",
|
|
35
|
+
"tsdown": "^0.22.14",
|
|
36
|
+
"typescript": "^6.0.3",
|
|
37
|
+
"vitest": "^4.1.11"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@onereach/state-machine-step-service": "1.0.0-framework.11",
|
|
41
|
+
"@onereach/ts-memoize": "^1.0.1",
|
|
42
|
+
"source-map-support": "^0.5.21",
|
|
43
|
+
"timestring": "^7.0.0",
|
|
44
|
+
"tslib": "2.8.1",
|
|
45
|
+
"zod": "^4.5.4"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsdown --config tsdown.config.mts",
|
|
49
|
+
"build:visualize": "VISUALIZE=1 pnpm build",
|
|
50
|
+
"preversion_": "pnpm build && pnpm test",
|
|
51
|
+
"publish:rc": "npm version prerelease --preid rc && npm publish --tag rc",
|
|
52
|
+
"test": "npm run unit",
|
|
53
|
+
"unit": "vitest run",
|
|
54
|
+
"preversion": "pnpm build"
|
|
55
|
+
}
|
|
56
|
+
}
|