@onereach/step-helpers 0.0.0-stage → 0.2.0-framework.1

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 CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # @onereach/step-helpers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reusable OneReach Flow SDK utilities, independent of the state-machine framework.
4
+ One package provides explicit entry points, without a root barrel:
5
+
6
+ | Entry point | Exports |
7
+ | ----------- | ------- |
8
+ | `@onereach/step-helpers/decorators` | `createMethodDecoratorWithOptionalArguments`, `AnyFunction`, `MethodDecoratorWithOptionalArguments` |
9
+ | `@onereach/step-helpers/sdk` | `validateFlowSdkVersion` |
10
+ | `@onereach/step-helpers/services` | `ThreadServiceWithData` |
11
+ | `@onereach/step-helpers/threads` | `runChildThread`, `isThreadBusy`, `listChildThreads`, `stopThread`, `endChildThreads`, `ManagedThreadLocal`, `ManagedThreadConfig` |
12
+
13
+ TypeScript is the authored source; published files are ESM (`.mjs`) with `.d.mts`
14
+ declarations and source maps. Consumers do not need to compile TypeScript.
15
+ The package declares `sideEffects: false`, allowing unused modules and exports to
16
+ be tree-shaken. The Flow SDK is an external peer, not bundled or re-exported.
17
+ There is no dependency on `@onereach/step-state-machine-shared`.
18
+
19
+ ## Usage and bundling
20
+
21
+ ```ts
22
+ import { createMethodDecoratorWithOptionalArguments } from '@onereach/step-helpers/decorators';
23
+ import { validateFlowSdkVersion } from '@onereach/step-helpers/sdk';
24
+ import { ThreadServiceWithData } from '@onereach/step-helpers/services';
25
+ import { runChildThread, stopThread } from '@onereach/step-helpers/threads';
26
+ ```
27
+
28
+ For a bundled step, add the package as a build/dev dependency and opt it into the
29
+ consumer's bundler. For example, with tsdown:
30
+
31
+ ```ts
32
+ deps: {
33
+ neverBundle: true,
34
+ alwaysBundle: [/^@onereach\/step-helpers(?:\/|$)/],
35
+ }
36
+ ```
37
+
38
+ This includes only used helper code while leaving the Flow SDK external.
39
+ Both state-machine steps use this configuration for JavaScript and declaration
40
+ bundling, so their published files do not require `step-helpers` at runtime.
41
+ Other consumers may intentionally keep it external and declare a runtime dependency.
42
+
43
+ The helpers retain their existing behavior:
44
+
45
+ - Managed children use `local.parent` and `local.active`. Starting a busy child
46
+ requires explicit `force`; reuse requires a supplied state.
47
+ - Shutdown optionally stops descendants, marks a thread inactive before its
48
+ ending action, and awaits the SDK run. It is not cancellation of arbitrary
49
+ JavaScript work. `endChildThreads` settles siblings and throws failures by
50
+ default; `{ throw: false }` returns the settled results.
51
+ - The decorator factory supports legacy TypeScript method decorators, both bare
52
+ and with options; it preserves the wrapped method name where possible. It is
53
+ not a Stage 3 decorator API.
54
+ - `validateFlowSdkVersion('8.0.72')` reads the installed SDK manifest on each call,
55
+ accepts its numeric version prefix, and rejects unsupported versions.
56
+ - `ThreadServiceWithData` keeps the supplied configuration object by reference.
57
+
58
+ ## Migration and ownership
59
+
60
+ The duplicated service, decorator factory, thread helpers, and version check were
61
+ extracted from both state-machine step packages. Import these public entry points
62
+ instead of the former step-local source files; there are no forwarding aliases.
63
+ Unused cached abort-controller helpers were removed rather than carried over.
64
+ No cancellation API is provided.
65
+
66
+ State-machine error mapping and foreground/background error decorators remain in
67
+ their owning integration/step packages. Placeholder main-state fields and the
68
+ unimplemented `customizeInitialValue` option are not part of this extraction.
69
+
70
+ ## Verification
71
+
72
+ ```sh
73
+ pnpm exec turbo run build --filter=@onereach/step-helpers
74
+ pnpm --filter @onereach/step-helpers exec vitest run
75
+ ```
76
+
77
+ `pnpm unit:tools` builds and tests all tools separately from `pnpm test`.
78
+ Tests cover the public build artifacts, actual consumer bundling/tree shaking,
79
+ managed thread behavior, decorators, services, and SDK compatibility checks.
@@ -0,0 +1,12 @@
1
+ //#region src/decorators.d.ts
2
+ /**
3
+ * Creates a method decorator that can be used with or without options.
4
+ * @param apply - Function that applies the decorator logic with given options.
5
+ * @param defaultOptions - Default options to use if none are provided.
6
+ */
7
+ declare function createMethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction>(apply: (options: A, target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => T | TypedPropertyDescriptor<T> | void, defaultOptions: A): MethodDecoratorWithOptionalArguments<A, T>;
8
+ type AnyFunction = (...arguments_: any[]) => any;
9
+ type MethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction> = ((target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void) & ((options?: A) => MethodDecorator);
10
+ //#endregion
11
+ export { AnyFunction, MethodDecoratorWithOptionalArguments, createMethodDecoratorWithOptionalArguments };
12
+ //# sourceMappingURL=decorators.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.d.mts","names":[],"sources":["../src/decorators.ts"],"mappings":";;;;;;iBAOgB,2CAA2C,GAAG,UAAU,cAAc,aACpF,QACE,SAAS,GACT,gBACA,8BACA,YAAY,wBAAwB,OACjC,IAAI,wBAAwB,WACjC,gBAAgB,IACf,qCAAqC,GAAG;KAsD/B,kBAAkB;KAElB,qCAAqC,GAAG,UAAU,cAAc,iBAGxE,gBACA,8BACA,YAAY,wBAAwB,OACjC,wBAAwB,eAEzB,UAAU,MAAM"}
@@ -0,0 +1,2 @@
1
+ function e(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)}}export{e as createMethodDecoratorWithOptionalArguments};
2
+ //# sourceMappingURL=decorators.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.mjs","names":[],"sources":["../src/decorators.ts"],"sourcesContent":["/* 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"],"mappings":"AAOA,SAAgB,EACd,EAMA,EAC4C,CAC5C,SAAS,EACP,EACA,EACA,EACA,EACmC,CACnC,IAAM,EAAQ,EAAM,EAAS,EAAQ,EAAa,CAAU,EAG5D,GAAI,OAAO,GAAU,WAAY,CAC/B,IAAM,EAAiB,EAAW,MAC5B,EAAgB,EAEtB,GAAI,GAAgB,MAAQ,KAC1B,GAAI,CACF,OAAO,eAAe,EAAe,OAAQ,CAAE,MAAO,EAAe,IAAK,CAAC,CAC7E,MAAQ,CAER,CAIF,MADA,GAAW,MAAQ,EACZ,CACT,CAGA,OAAO,GAAS,CAClB,CAEA,OAAO,SACL,EACA,EACA,EACK,CACL,GACE,IAAc,MACd,IAAc,MACd,OAAO,GAAc,UACrB,OAAO,GAAc,WACpB,OAAO,GAAc,UAAY,OAAO,GAAc,UAGvD,OAAO,EAAS,EAAgB,EAAW,EAAW,CAAS,EAIjE,IAAM,EAAW,GAAmB,EACpC,OAAQ,EAAgB,EAA8B,IAC7C,EAAS,EAAS,EAAQ,EAAa,CAAU,CAE5D,CACF"}
package/dist/sdk.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ //#region src/sdk.d.ts
2
+ declare function validateFlowSdkVersion(minVersion: string): Promise<void>;
3
+ //#endregion
4
+ export { validateFlowSdkVersion };
5
+ //# sourceMappingURL=sdk.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk.d.mts","names":[],"sources":["../src/sdk.ts"],"mappings":";iBAKsB,uBAAuB,qBAAqB"}
package/dist/sdk.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{createRequire as e}from"node:module";import{readFile as t}from"node:fs/promises";const n=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 r=n.resolve(`@onereach/flow-sdk/package.json`);if(!r)throw Error(`Could not find package.json for @onereach/flow-sdk`);let i=await t(r,`utf8`),{version:a}=JSON.parse(i),{groups:o}=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)/.exec(a)||{};if(!o)throw Error(`Invalid Flow SDK version format: ${a}`);let s=Math.trunc(Number(o.major??`0`)),c=Math.trunc(Number(o.minor??`0`)),l=Math.trunc(Number(o.patch??`0`));if(s==null||c==null||l==null||Number.isNaN(s)||Number.isNaN(c)||Number.isNaN(l))throw Error(`Invalid version format: ${a}`);let[u,d,f]=e.split(`.`).map(e=>Math.trunc(Number(e)));if(u==null||d==null||f==null||Number.isNaN(u)||Number.isNaN(d)||Number.isNaN(f))throw Error(`Invalid minimum version format: ${e}`);if(s<u||s===u&&c<d||s===u&&c===d&&l<f)throw Error(`Flow SDK version '${a}' is lower than required minimum version '${e}' for the step`)}export{r as validateFlowSdkVersion};
2
+ //# sourceMappingURL=sdk.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk.mjs","names":[],"sources":["../src/sdk.ts"],"sourcesContent":["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"],"mappings":"wFAGA,MAAM,EAAU,EAAc,YAAY,GAAG,EAE7C,eAAsB,EAAuB,EAAmC,CAC9E,GAAI,OAAO,GAAe,UAAY,CAAC,kBAAkB,KAAK,CAAU,EACtE,MAAU,MAAM,mCAAmC,GAAY,EAGjE,IAAM,EAAkB,EAAQ,QAAQ,iCAAiC,EACzE,GAAI,CAAC,EACH,MAAU,MAAM,oDAAoD,EAGtE,IAAM,EAAqB,MAAM,EAAS,EAAiB,MAAM,EAE3D,CAAE,WAAY,KAAK,MAAM,CAAkB,EAC3C,CAAE,UAAW,+CAA+C,KAAK,CAAO,GAAK,CAAC,EAEpF,GAAI,CAAC,EAAQ,MAAU,MAAM,oCAAoC,GAAS,EAE1E,IAAM,EAAQ,KAAK,MAAM,OAAO,EAAO,OAAS,GAAG,CAAC,EAC9C,EAAQ,KAAK,MAAM,OAAO,EAAO,OAAS,GAAG,CAAC,EAC9C,EAAQ,KAAK,MAAM,OAAO,EAAO,OAAS,GAAG,CAAC,EAEpD,GACE,GAAS,MACT,GAAS,MACT,GAAS,MACT,OAAO,MAAM,CAAK,GAClB,OAAO,MAAM,CAAK,GAClB,OAAO,MAAM,CAAK,EAElB,MAAU,MAAM,2BAA2B,GAAS,EAGtD,GAAM,CAAC,EAAU,EAAU,GAAY,EAAW,MAAM,GAAG,CAAC,CAAC,IAAK,GAAM,KAAK,MAAM,OAAO,CAAC,CAAC,CAAC,EAE7F,GACE,GAAY,MACZ,GAAY,MACZ,GAAY,MACZ,OAAO,MAAM,CAAQ,GACrB,OAAO,MAAM,CAAQ,GACrB,OAAO,MAAM,CAAQ,EAErB,MAAU,MAAM,mCAAmC,GAAY,EAGjE,GACE,EAAQ,GACP,IAAU,GAAY,EAAQ,GAC9B,IAAU,GAAY,IAAU,GAAY,EAAQ,EAErD,MAAU,MACR,qBAAqB,EAAQ,4CAA4C,EAAW,eACtF,CAEJ"}
@@ -0,0 +1,10 @@
1
+ import { BasicThreadService } from "@onereach/flow-sdk/services/basic.js";
2
+ import { CONFIG, IN, IThread } from "@onereach/flow-sdk/types/index.js";
3
+ //#region src/services.d.ts
4
+ declare class ThreadServiceWithData<TConfig extends CONFIG, TData extends IN<CONFIG> = IN<TConfig>> extends BasicThreadService<TConfig> {
5
+ protected readonly data: TData;
6
+ constructor(thread: IThread<TConfig>, data: TData);
7
+ }
8
+ //#endregion
9
+ export { ThreadServiceWithData };
10
+ //# sourceMappingURL=services.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services.d.mts","names":[],"sources":["../src/services.ts"],"mappings":";;;cAGa,sBACX,gBAAgB,QAChB,cAAc,GAAG,UAAU,GAAG,kBACtB,mBAAmB;qBACR,MAAM;EAEb,YAAA,QAAQ,QAAQ,UAAU,MAAM"}
@@ -0,0 +1,2 @@
1
+ import{BasicThreadService as e}from"@onereach/flow-sdk/services/basic.js";var t=class extends e{data;constructor(e,t){super(e),this.data=t}};export{t as ThreadServiceWithData};
2
+ //# sourceMappingURL=services.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services.mjs","names":[],"sources":["../src/services.ts"],"sourcesContent":["import { BasicThreadService } from '@onereach/flow-sdk/services/basic.js';\nimport type { CONFIG, IN, IThread } from '@onereach/flow-sdk/types/index.js';\n\nexport class ThreadServiceWithData<\n TConfig extends CONFIG,\n TData extends IN<CONFIG> = IN<TConfig>,\n> extends BasicThreadService<TConfig> {\n protected readonly data: TData;\n\n constructor(thread: IThread<TConfig>, data: TData) {\n super(thread);\n this.data = data;\n }\n}\n"],"mappings":"0EAGA,IAAa,EAAb,cAGU,CAA4B,CACpC,KAEA,YAAY,EAA0B,EAAa,CACjD,MAAM,CAAM,EACZ,KAAK,KAAO,CACd,CACF"}
@@ -0,0 +1,29 @@
1
+ import { CONFIG, IThread, IThreadId, IThreadOptions, RESULT } from "@onereach/flow-sdk/types/index.js";
2
+ //#region src/threads.d.ts
3
+ /**
4
+ * Runs a new thread or reuses an existing one (if it ended).
5
+ * @param thread The step to run the thread for.
6
+ * @throws Error if the thread is not ended or if the state is not provided.
7
+ */
8
+ declare function runChildThread<ThreadConfig extends CONFIG & ManagedThreadConfig, StepConfig extends CONFIG>(thread: IThread<StepConfig>, { id, state, local, ...options }: IThreadOptions<ThreadConfig>, { force }?: {
9
+ force?: boolean;
10
+ }): Promise<RESULT<ThreadConfig>>;
11
+ declare function isThreadBusy<StepConfig extends CONFIG, ThreadConfig extends CONFIG & ManagedThreadConfig>(thread: IThread<StepConfig>, threadId: IThreadId): boolean;
12
+ declare function listChildThreads<StepConfig extends CONFIG, ChildThreadConfig extends CONFIG & ManagedThreadConfig>(thread: IThread<StepConfig>, parentThreadId?: IThreadId): IThread<ChildThreadConfig>[];
13
+ declare function stopThread<ThreadConfig extends CONFIG & ManagedThreadConfig, StepConfig extends CONFIG>(thread: IThread<StepConfig>, id: IThreadId, { result, stopChildThreads }?: {
14
+ result?: RESULT<ThreadConfig>;
15
+ stopChildThreads?: boolean;
16
+ }): Promise<void>;
17
+ declare function endChildThreads<ThreadConfig extends CONFIG, StepConfig extends CONFIG>(thread: IThread<StepConfig>, result?: RESULT<ThreadConfig>, options?: {
18
+ throw?: boolean;
19
+ }): Promise<PromiseSettledResult<void>[]>;
20
+ type ManagedThreadLocal = {
21
+ active: boolean;
22
+ parent: IThreadId;
23
+ };
24
+ type ManagedThreadConfig = {
25
+ local: ManagedThreadLocal;
26
+ };
27
+ //#endregion
28
+ export { ManagedThreadConfig, ManagedThreadLocal, endChildThreads, isThreadBusy, listChildThreads, runChildThread, stopThread };
29
+ //# sourceMappingURL=threads.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"threads.d.mts","names":[],"sources":["../src/threads.ts"],"mappings":";;;;;;;iBAOsB,eAAe,qBAAqB,SAAS,qBAAqB,mBAAmB,QACzG,QAAQ,QAAQ,eACd,IAAI,OAAO,UAAU,WAAW,eAAe,iBAC/C;EAAW;IACZ,QAAQ,OAAO;iBAiCF,aAAa,mBAAmB,QAAQ,qBAAqB,SAAS,qBACpF,QAAQ,QAAQ,aAChB,UAAU;iBAMI,iBAAiB,mBAAmB,QAAQ,0BAA0B,SAAS,qBAC7F,QAAQ,QAAQ,aAChB,iBAAgB,YACf,QAAQ;iBASW,WAAW,qBAAqB,SAAS,qBAAqB,mBAAmB,QACrG,QAAQ,QAAQ,aAChB,IAAI,aACF,QAAQ;EAAsB,SAAS,OAAO;EAAe;IAC9D;iBAgBmB,gBAAgB,qBAAqB,QAAQ,mBAAmB,QACpF,QAAQ,QAAQ,aAChB,SAAS,OAAO,eAChB;EAAW;IACV,QAAQ;KAgBC;EACV;EACA,QAAQ;;KAGE;EACV,OAAO"}
@@ -0,0 +1,2 @@
1
+ async function e(e,{id:t,state:n,local:r,...i},{force:a}={}){let o=e.process.getThread(t);if(e.log.DEBUG?.(`runThread: thread with id '${t}'`,i),o==null)return await e.thread.runThread({...i,id:t,state:n,local:{...r,parent:e.thread.id,active:!0}});if(!a&&!o.ended&&o.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 o.local.active=!0,await o.enqueueAndRun({name:`goto`,state:{...n,active:!0}})}function t(e,t){let n=e.process.getThread(t);return n!=null&&n.local.active&&!n.ended}function n(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 r(e,t,{result:n,stopChildThreads:r}={}){let a=e.process.getThread(t);e.log.DEBUG?.(`stopThread: thread with id '${t}'`),a&&(r&&await i(a,n),a.local.active&&(a.local.active=!1,!a.ended&&await a.enqueueAndRun({name:`ending`,result:n})))}async function i(e,t,i={}){let a=n(e).map(async n=>await r(e,n.id,{stopChildThreads:!0,result:t})),o=await Promise.allSettled(a);if(i.throw??!0){let e=o.find(e=>e.status===`rejected`);if(e)throw e.reason}return o}export{i as endChildThreads,t as isThreadBusy,n as listChildThreads,e as runChildThread,r as stopThread};
2
+ //# sourceMappingURL=threads.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"threads.mjs","names":[],"sources":["../src/threads.ts"],"sourcesContent":["import 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: '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: '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"],"mappings":"AAOA,eAAsB,EACpB,EACA,CAAE,KAAI,QAAO,QAAO,GAAG,GACvB,CAAE,SAA+B,CAAC,EACH,CAC/B,IAAM,EAAc,EAAO,QAAQ,UAAwB,CAAE,EAG7D,GAFA,EAAO,IAAI,QAAQ,8BAA8B,EAAG,GAAI,CAAO,EAE3D,GAAe,KAEjB,OAAO,MAAM,EAAO,OAAO,UAAwB,CACjD,GAAG,EACH,KACA,QACA,MAAO,CACL,GAAG,EACH,OAAQ,EAAO,OAAO,GACtB,OAAQ,EACV,CACF,CAAC,EAGH,GAAI,CAAC,GAAS,CAAC,EAAY,OAAS,EAAY,MAAM,OACpD,MAAU,MAAM,mBAAmB,EAAG,2CAA2C,EACnF,GAAI,GAAS,KAAW,MAAU,MAAM,mBAAmB,EAAG,2BAA2B,EAIzF,MADA,GAAY,MAAM,OAAS,GACpB,MAAM,EAAY,cAAc,CACrC,KAAM,OACN,MAAO,CACL,GAAG,EACH,OAAQ,EACV,CACF,CAAC,CACH,CAEA,SAAgB,EACd,EACA,EACS,CACT,IAAM,EAAgB,EAAO,QAAQ,UAAwB,CAAQ,EACrE,OAAO,GAAiB,MAAa,EAAc,MAAM,QAAU,CAAC,EAAc,KACpF,CAEA,SAAgB,EACd,EACA,EAA4B,EAAO,GACL,CAC9B,IAAM,EAAe,CAAC,EACtB,IAAK,IAAM,KAAY,EAAO,QAAQ,QAAS,CAC7C,IAAM,EAAO,EAAO,QAAQ,QAAQ,GAChC,GAAM,MAAM,SAAW,GAAgB,EAAa,KAAK,CAAI,CACnE,CACA,OAAO,CACT,CAEA,eAAsB,EACpB,EACA,EACA,CAAE,SAAQ,oBAAoF,CAAC,EAChF,CACf,IAAM,EAAe,EAAO,QAAQ,UAAwB,CAAE,EAC9D,EAAO,IAAI,QAAQ,+BAA+B,EAAG,EAAE,EAElD,IAED,GAAkB,MAAM,EAAgB,EAAc,CAAM,EAE3D,EAAa,MAAM,SAExB,EAAa,MAAM,OAAS,GACxB,GAAa,OAEjB,MAAM,EAAa,cAAc,CAAE,KAAM,SAAU,QAAO,CAAC,GAC7D,CAEA,eAAsB,EACpB,EACA,EACA,EAA+B,CAAC,EACO,CAEvC,IAAM,EADe,EAAiB,CACT,CAAC,CAAC,IAC7B,KAAO,IAAU,MAAM,EAAW,EAAQ,EAAM,GAAI,CAAE,iBAAkB,GAAM,QAAO,CAAC,CACxF,EACM,EAAc,MAAM,QAAQ,WAAW,CAAS,EAGtD,GADqB,EAAQ,OAAS,GACpB,CAChB,IAAM,EAAa,EAAY,KAAM,GAAS,EAAK,SAAW,UAAU,EACxE,GAAI,EAAY,MAAM,EAAW,MACnC,CAEA,OAAO,CACT"}
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@onereach/step-helpers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0-framework.1",
4
+ "description": "Reusable OneReach Flow SDK step utilities",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "engines": {
9
+ "node": ">=22.11"
10
+ },
11
+ "exports": {
12
+ "./decorators": "./dist/decorators.mjs",
13
+ "./sdk": "./dist/sdk.mjs",
14
+ "./services": "./dist/services.mjs",
15
+ "./threads": "./dist/threads.mjs",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "peerDependencies": {
25
+ "@onereach/flow-sdk": "v9.0.0-monosplit.5"
26
+ },
27
+ "devDependencies": {
28
+ "@arethetypeswrong/core": "^0.18.5",
29
+ "@onereach/flow-sdk": "v9.0.0-monosplit.5",
30
+ "@types/node": "^24.13.3",
31
+ "publint": "^0.3.24",
32
+ "tsdown": "^0.22.14",
33
+ "tslib": "2.8.1",
34
+ "typescript": "^6.0.3",
35
+ "vitest": "^4.1.11"
36
+ },
37
+ "scripts": {
38
+ "build": "tsdown --config tsdown.config.mts",
39
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile .cache/typecheck/source.tsbuildinfo && tsc --noEmit -p test/tsconfig.json --incremental --tsBuildInfoFile .cache/typecheck/test.tsbuildinfo",
40
+ "unit": "vitest run",
41
+ "unit:coverage": "vitest run --coverage"
42
+ }
6
43
  }