@onereach/step-state-machine-shared 0.0.0-stage → 1.0.0-framework.13

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,282 @@
1
- # Temporary Holding Version
1
+ # @onereach/step-state-machine-shared
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
+ This workspace package owns shared OneReach step support under `steps/shared`.
4
+ It combines process-level framework composition with configuration normalization,
5
+ Flow error classification, and reusable step test suites. It is not an
6
+ engine-independent framework component or an SDK step implementation.
7
+
8
+ It selects the JSON Schema compiler and OneReach drivers and assembles framework
9
+ services through `getStateMachineSystem(process)`. `StateMachineThreadService`
10
+ remains available as a thread-service convenience wrapper. Flow SDK
11
+ dependencies are intentional here; they must not leak into core contracts,
12
+ validation, stores, or runtime. Step classes, schemas, listeners, broadcasts,
13
+ and concrete error classes remain in their owning step packages.
14
+
15
+ Generic SDK services, thread utilities, the method-decorator factory, and SDK
16
+ version checks live in [`@onereach/step-helpers`](../../tools/step-helpers/README.md)
17
+ under `tools/`, not in this state-machine composition package.
18
+
19
+ ## Package entry points
20
+
21
+ | Import | Ownership |
22
+ | ------ | --------- |
23
+ | `@onereach/step-state-machine-shared` | System factories, thread service, function-lookup consumer types, configuration conflict error, and existing framework type/error re-exports. |
24
+ | `@onereach/step-state-machine-shared/configuration` | Step data-in normalization and `DataInValidationError`. |
25
+ | `@onereach/step-state-machine-shared/errors` | Shared error filter factory, framework mapping, and step error-code types. |
26
+ | `@onereach/step-state-machine-shared/notifications` | Flow invalidation routing, best-effort publication diagnostics, and bounded serial refresh scheduling. |
27
+ | `@onereach/step-state-machine-shared/testing` | Reusable configuration and error-filter test suites; requires Vitest, an optional peer used only by this entry point. |
28
+
29
+ Implementation modules stay separated under `src/system`, `src/configuration`,
30
+ `src/errors`, `src/notifications`, and `src/testing`; consumers use package entry points rather than
31
+ cross-directory source imports. Builds follow workspace dependencies, so changing
32
+ shared support no longer invalidates unrelated framework builds through Turbo
33
+ global dependencies. Build dependencies before running package tests:
34
+
35
+ ```sh
36
+ pnpm exec turbo run build --filter=@onereach/step-state-machine-shared
37
+ pnpm --filter @onereach/step-state-machine-shared exec vitest run
38
+ ```
39
+
40
+ Shared configuration-generation tests run child processes from the consuming
41
+ step's directory, resolving its declared generator dependency rather than
42
+ requiring workspace packages to be installed at the repository root.
43
+
44
+ ### Migration from step-service
45
+
46
+ `@onereach/state-machine-step-service` has been replaced by this package and removed
47
+ from the workspace without a compatibility alias. Change its imports/dependencies
48
+ to `@onereach/step-state-machine-shared`. Root composition APIs and class names
49
+ remain unchanged. Replace old relative shared-helper imports with the subpaths
50
+ above. Pending changesets target the new package.
51
+
52
+ The relocation itself does not change the process cache key or configuration
53
+ identity, TTL ownership, execution, or error mapping. The subsequently implemented
54
+ notification behavior is described below and in the owning step guides.
55
+
56
+ ## Cached function convenience API
57
+
58
+ The initialization step installs a frozen `process.cache.stateMachines` facade
59
+ exposing only `getFunction(instanceId, functionName)`. Session registration
60
+ enables restoration after the flow first passes through initialization and
61
+ selects notification targets; it is not an execution authorization boundary.
62
+ Once available, lookup may target any persisted instance, including one created
63
+ by another flow. Missing instances and unknown functions reject during ordinary
64
+ service execution.
65
+
66
+ The private registry is retained under a versioned process-cache key, so
67
+ separately bundled copies of initialization code share the same registration
68
+ state and facade. Each lookup returns a lightweight wrapper rather than caching
69
+ wrapper identity; actual executable preparation remains cached by the framework.
70
+
71
+ Returned callables keep their original instance ID and read its current
72
+ persisted state on every call. Reinitializing a step or changing routing does not
73
+ retarget or revoke an already-retrieved function. Agent/skill selection and
74
+ handoff policy belong to the agent dispatcher, not the state-machine service.
75
+
76
+ The Execute State Machine Function step remains independent of initialization
77
+ and this convenience facade. Separate flows can execute persisted instances
78
+ directly by instance ID, function name, arguments, and context.
79
+
80
+ ## Flow notifications
81
+
82
+ `publishStateChange(thread, identity, options)` sends invalidation hints for
83
+ `{ instanceId, templateId }`. Local delivery targets the selected initialization
84
+ step through `localStepId`; remote delivery is enabled with `remote: true`.
85
+ Callers can alternatively supply `localStepIds` for multiple targets; duplicate
86
+ step IDs are deduplicated and remote delivery is attempted once.
87
+ All policy properties and recipient iterables are resolved into a per-call
88
+ snapshot before delivery starts, so policy errors cannot interrupt partial delivery
89
+ or discard earlier transport diagnostics.
90
+ Inactive targets are reported by default. `skipInactiveLocalTargets: true`
91
+ explicitly permits absent/ended listeners for consumers whose execution does not
92
+ require listening.
93
+ The adapter owns event names and listener thread addressing. Remote identity
94
+ segments are independently URI-encoded to avoid slash collisions; account/topic
95
+ scope and authorization remain the SDK's responsibility.
96
+
97
+ Each requested channel is attempted independently. Rejections, returned SDK
98
+ `Error` results, and inactive local targets become serializable
99
+ `NotificationFailure` records (`channel`, `message`), plus best-effort warning
100
+ logs. Even logging failure cannot turn a caught transport failure into a failed
101
+ mutation. No channel or mutation is automatically retried.
102
+
103
+ `executeStateMachineFunction(thread, service, request, context, notifications?)`
104
+ shares execution/post-commit orchestration across cached callables and the
105
+ execution step. It calls the service exactly once, publishes only for successful
106
+ mutations, and returns `{ result, notificationFailures }`. Queries and rejected
107
+ executions never publish. Publication options can be supplied directly or through
108
+ a callback evaluated after commit to select current recipients. Notification
109
+ failure records/logging do not replace committed results. Routing-policy callbacks
110
+ and publication setup are also contained after commit: failures return
111
+ `{ channel: 'policy', message }` and best-effort warnings, without replaying execution.
112
+ Transport failures retain `channel: 'local'` or `'remote'`.
113
+ An optional final execution-options argument forwards per-call cancellation
114
+ signals to the service without imposing initialization or agent-routing policy.
115
+
116
+ The root also exports the `StateMachineFunctions` lookup interface and
117
+ `CachedStateMachineFunction` callable type, allowing consumers to type
118
+ `process.cache.stateMachines` without importing initialization-step internals.
119
+ The interface exposes only `getFunction(instanceId, functionName)`. Function
120
+ lookup is lazy; the framework service validates names and input on invocation.
121
+
122
+ `LatestStateRefresh` serializes loads with at most one pending refresh hint.
123
+ Eligible sources select callback routing; ineligible hints still invalidate the
124
+ projection without erasing an already pending eligible source. The initialization
125
+ step separately selects a bounded observed-snapshot callback queue (default) or
126
+ one coalesced pending callback reading live output (`latest-state`). Promise state
127
+ is never persisted in SDK thread state.
128
+
129
+ These are best-effort, in-process synchronization tools, not a durable event log:
130
+ intermediate changes may be skipped, source labels identify hints rather than
131
+ prove mutation provenance, and missed hints may leave projections stale.
132
+ Publication still awaits SDK transport calls; process crashes or a broader SDK
133
+ timeout/cancellation after commit remain ambiguous and are not rollback.
134
+ See the [initialization/listener guide](../step-initialize-state-manager/README.md#latest-state-synchronization)
135
+ and [execution guide](../step-execute-state-machine-function/README.md#post-commit-notifications).
136
+
137
+ The composition root explicitly constructs `AjvJsonSchemaValidatorCompiler` and
138
+ `CachedStateTemplatePreparer`, then injects the preparer's structural `prepare` /
139
+ `bind` capability into the template store. Framework stores do not select engines
140
+ or cache decorators. Instance stores and services accept consumer-owned narrow
141
+ interfaces; the selected concrete implementations satisfy them directly.
142
+
143
+ ## Complete-system composition
144
+
145
+ `createStateMachineSystem(process, options?)` constructs the compiler, preparer,
146
+ drivers, stores, runtime, and service as local values and returns one complete
147
+ `StateMachineProcessCache<TContext>`. It does not publish to the process cache.
148
+ The aggregate and its `configuration` record are shallowly frozen; the process,
149
+ cache facade, and infrastructure objects are not frozen.
150
+
151
+ `getStateMachineSystem(process, options?)` retrieves that complete system or
152
+ constructs and publishes it only after every constructor succeeds.
153
+ `StateMachineThreadService` delegates to this operation and exposes its service.
154
+ A constructor failure leaves no entry behind; a later call may retry, including
155
+ with different options. Construction is synchronous, so there is no in-flight
156
+ promise entry. No background resource or speculative disposal framework is added;
157
+ the SDK process owns the lifetime and supplied cache facades remain externally owned.
158
+
159
+ ### Configuration identity and reuse
160
+
161
+ One system is retained per process under `STATE_MACHINE_PROCESS_CACHE_KEY`
162
+ (`sm:or-mf:json-schema-ajv:v6`). Use that export or `service.cacheKey` rather than
163
+ hardcoding the key. The namespace does not reuse or modify legacy `v1`, `v2`,
164
+ unlocked `v3`, pre-lifetime-retention `v4`, or pre-compiler-policy `v5` entries.
165
+
166
+ - On first construction, `cache` defaults to the SDK `Cache` facade.
167
+ - On retrieval, omitted/undefined cache options inherit the established facade.
168
+ - Steps inherit process infrastructure rather than accepting cache facades in
169
+ Data In. Tests configure isolated facades in request setup (including restored
170
+ invocations), exposed as a fixture `cache` option rather than `_testSettings`.
171
+ - Explicit cache overrides must be the **same object**, not merely have equivalent properties/methods.
172
+ Conflicts throw `StateMachineConfigError` with `option` set to
173
+ `cache`, leaving the existing system intact.
174
+ - `executionLock` configures `acquireTimeoutMs` (default 10,000), `leaseDurationMs`
175
+ (default 30,000), and `retryDelayMs` (default 100). Omitted fields inherit the
176
+ established policy; conflicting explicit fields throw `StateMachineConfigError`
177
+ with `option: 'executionLock'`. Durations are safe integer milliseconds within
178
+ the timer range; acquisition may be zero, retries must be positive, and the
179
+ lease must be at least three milliseconds.
180
+ - `implementationCompiler` is optional backend policy. Initially omitted means
181
+ trusted JavaScript; later omission inherits the established compiler. Explicit
182
+ compiler objects must have identical object identity, or
183
+ `StateMachineConfigError` reports `option: 'implementationCompiler'`.
184
+ The system does not import, construct, or automatically select a worker backend.
185
+ - Storage scope is the owning process identity plus its account ID and account
186
+ slug snapshot, using the drivers' fixed account-global merge-field key layout.
187
+ Reusing an entry under another process/account throws the same error with
188
+ `option: 'storageScope'`.
189
+ - AJV defaults, preparation/store cache policies, runtime context policy, service
190
+ concurrency guard, and driver key layout are fixed by this integration version,
191
+ not caller-selectable options. Future configurable policies must participate in
192
+ identity checking rather than silently changing a live system.
193
+
194
+ To opt pure functions into terminable execution, construct
195
+ [`WorkerImplementationCompiler`](../../packages/state-machine-runtime-node-worker/README.md)
196
+ and supply it before the first process-system construction. It automatically
197
+ selects functions declaring `annotations.pure: true`; an optional selector can
198
+ narrow this policy. Empty capabilities or idempotency alone do not establish
199
+ purity. The declaration does not enable a backend by itself. Worker execution
200
+ receives JSON data, never Flow context or SDK capabilities. The caller can still
201
+ receive a timeout before worker exit, but the coordinator retains ownership until
202
+ exit is confirmed. Non-selected host-integrated functions keep the trusted,
203
+ fail-closed path. Deploy the engine policy consistently across all writers.
204
+
205
+ ### Distributed instance execution locks
206
+
207
+ Composition explicitly injects `OneReachExecutionLocks` from
208
+ `@onereach/state-machine-coordination-onereach` into every service. The framework
209
+ integration owns distributed acquisition, renewal, keys, and release; this step
210
+ package owns only selecting the cache/account scope, canonical storage-key
211
+ resolver, and process policy.
212
+ Separate flows/workers sharing the backend and account-global instance storage
213
+ coordinate, while different instances remain concurrent.
214
+
215
+ Execution, creation, state replacement, and deletion acquire ownership before
216
+ loading/writing. Mutations keep ownership until persistence completes; waiting
217
+ callers load fresh state after acquisition. Executed queries also participate.
218
+ Notifications run after the service returns, outside the execution lock.
219
+ Plain reads and direct store/driver writes do not participate.
220
+
221
+ Acquisition timeout raises `ExecutionLockTimeoutError` (`TIMEOUT` in Flow);
222
+ ownership loss raises `ExecutionLockLostError` (`CONFLICT`). Other acquisition
223
+ failures retain their cause in `ExecutionLockAcquireError`.
224
+ Execution-lock release failures after the protected operation settles preserve its
225
+ result/error and produce best-effort process warnings, not a mutation failure or
226
+ automatic retry. Warning failures are contained; pending warning reports do not
227
+ delay the result. These diagnostics are separate from notification failures.
228
+ Callers can pass an optional third `{ signal }` argument to `service.execute` to
229
+ cancel before user code starts. Signals remain per-call and are not cached or
230
+ persisted; SDK request/flow termination is not automatically wired to them.
231
+ Once user code starts, cancellation does not terminate or roll back the mutation.
232
+ Runtime timeout similarly does not terminate code. The service returns the timeout
233
+ without persisting a candidate, while the provider keeps ownership until actual
234
+ execution completion. Retention, settlement, and ownership-loss diagnostics use
235
+ best-effort process logging. Unsettled work remains fail-closed; never force-unlock
236
+ a still-running worker. All writers must be deployed together to use this policy.
237
+
238
+ See the integration's
239
+ [execution coordination and persistence-lock guarantees](../../packages/state-machine-coordination-onereach/README.md).
240
+ Execution leases remain cooperative, not fenced. The driver's independent write
241
+ locks remain enabled, and a configured provider never falls back to unlocked
242
+ execution on failure. Core services can omit the provider explicitly; OneReach
243
+ step composition always supplies it.
244
+ Deploy all writers together; old `v3` services and direct writes do not acquire
245
+ execution locks, and `v4` services do not retain timed-out execution lifetimes.
246
+
247
+ For example, all of these reuse one complete system:
248
+
249
+ ```ts
250
+ const system = getStateMachineSystem(process, { cache });
251
+ getStateMachineSystem(process);
252
+ getStateMachineSystem(process, { cache });
253
+ ```
254
+
255
+ This replaces first-initialization-wins behavior for conflicting **explicit**
256
+ options. Callers that need a different policy must use a separate process rather
257
+ than replacing fields in the aggregate. `StateMachineProcessCache` fields are now
258
+ readonly and include the effective `configuration`.
259
+
260
+ `instanceTtl` is no longer a composition option or part of process identity.
261
+ Creation selects `retention.ttlMs` on the instance; the driver reuses it for sliding
262
+ expiration on writes. One process can therefore handle instances with different
263
+ retention durations. Execution requires neither a configured TTL nor a reference
264
+ to initialization configuration. See the
265
+ [retention and migration guide](../../packages/state-machine-store/README.md#instance-retention-and-migration).
266
+
267
+ Factories accept only the process and infrastructure options, never a thread or
268
+ request context. Each `service.execute(request, context)` supplies its own context;
269
+ sharing prepared executables does not capture an earlier execution's context.
270
+ Broadcasts, error codes, and SDK listener behavior are unchanged; returned instance
271
+ envelopes now include retention and use persisted format version 2.
272
+
273
+ See [repository boundaries](../../docs/repository-boundaries.md).
274
+
275
+ ## Error exports
276
+
277
+ The package re-exports contract/schema validation, runtime function lookup/timeout,
278
+ and store errors so steps can identify framework failures through their existing
279
+ integration dependency. `StateMachineConfigError` identifies process configuration
280
+ conflicts. Flow-facing classification remains in the step layer; this package
281
+ re-exports framework errors unchanged, including coordination's execution-lock
282
+ acquisition, timeout, and ownership-loss errors.
@@ -0,0 +1,44 @@
1
+ //#region src/configuration/data-in.d.mts
2
+ interface DataInIssue {
3
+ path: string;
4
+ message: string;
5
+ }
6
+ declare class DataInValidationError extends Error {
7
+ readonly issues: readonly DataInIssue[];
8
+ constructor(issues: readonly DataInIssue[]);
9
+ }
10
+ interface CompiledIssue {
11
+ instancePath: string;
12
+ message?: string;
13
+ keyword: string;
14
+ params: Record<string, unknown>;
15
+ }
16
+ interface CompiledValidator {
17
+ (value: unknown): {
18
+ valid: boolean;
19
+ errors: readonly CompiledIssue[];
20
+ };
21
+ }
22
+ /**
23
+ * Copy only declared configuration fields, preserving opaque descendants.
24
+ * Invalid object shapes remain unchanged so the compiled validator rejects them.
25
+ */
26
+ declare function projectObject(value: unknown, fields: readonly string[]): unknown;
27
+ /**
28
+ * Preserve step merge-field normalization and the previous UTF-16 length limit.
29
+ * Portable JSON Schema additionally checks its standard code-point length rules.
30
+ */
31
+ declare function normalizeString(value: unknown, path: string, maxLength?: number): unknown;
32
+ /**
33
+ * Record envelopes are copied, but arbitrary argument/context values stay live.
34
+ * JSON Schema alone cannot distinguish a JavaScript record from a Map or class.
35
+ */
36
+ declare function copyRecord(value: unknown, path: string): unknown;
37
+ /**
38
+ * Normalize a fresh projection and validate it with AOT code.
39
+ * No defaults, coercion, or input mutation occur.
40
+ */
41
+ declare function parseStepDataIn<T>(value: unknown, fields: readonly string[], validate: CompiledValidator, normalize: (data: Record<string, unknown>) => void): T;
42
+ //#endregion
43
+ export { DataInIssue, DataInValidationError, copyRecord, normalizeString, parseStepDataIn, projectObject };
44
+ //# sourceMappingURL=configuration.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.d.mts","names":[],"sources":["../src/configuration/data-in.mts"],"mappings":";UAAiB;EACf;EACA;;cAGW,8BAA8B;WAChC,iBAAiB;EAEd,YAAA,iBAAiB;;UASrB;EACR;EACA;EACA;EACA,QAAQ;;UAGA;GACP;IAAmB;IAAgB,iBAAiB;;;;;;;iBAoBvC,cAAc,gBAAgB;;;;;iBAW9B,gBAAgB,gBAAgB,cAAc;;;;;iBAc9C,WAAW,gBAAgB;;;;;iBAa3B,gBAAgB,GAC9B,gBACA,2BACA,UAAU,mBACV,YAAY,MAAM,mCACjB"}
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,r,t as i}from"./data-in-DT43edEv.mjs";export{i as DataInValidationError,n as copyRecord,r as normalizeString,t as parseStepDataIn,e as projectObject};
@@ -0,0 +1,3 @@
1
+ var e=class extends Error{issues;constructor(e){super([`Invalid step configuration`,...e.map(e=>`${e.path||`/`}: ${e.message}`)].join(`
2
+ `)),this.name=`DataInValidationError`,this.issues=e}};function t(e){let t=e.instancePath;if(e.keyword===`required`&&typeof e.params.missingProperty==`string`){let n=e.params.missingProperty.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`);t+=`/${n}`}return{path:t,message:e.message??`Invalid value`}}function n(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function r(e,t){return n(e)?Object.fromEntries(t.filter(t=>t in e).map(t=>[t,e[t]])):e}function i(t,n,r){if(typeof t!=`string`)return t;let i=t.trim();if(i===`undefined`||i===`null`)throw new e([{path:n,message:`Unexpected undefined or null merge-field value`}]);if(r!==void 0&&i.length>r)throw new e([{path:n,message:`Must contain at most ${r} UTF-16 code units`}]);return i}function a(t,r){if(t===void 0)return t;if(!n(t))throw new e([{path:r,message:`Expected a record`}]);let i=Object.getPrototypeOf(t);if(i!==null&&i!==Object.prototype)throw new e([{path:r,message:`Expected a record`}]);return Object.fromEntries(Object.entries(t))}function o(i,a,o,s){let c=r(i,a);n(c)&&s(c);let l=o(c);if(!l.valid)throw new e(l.errors.map(e=>t(e)));return c}export{r as a,o as i,a as n,i as r,e as t};
3
+ //# sourceMappingURL=data-in-DT43edEv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-in-DT43edEv.mjs","names":[],"sources":["../src/configuration/data-in.mts"],"sourcesContent":["export interface DataInIssue {\n path: string;\n message: string;\n}\n\nexport class DataInValidationError extends Error {\n readonly issues: readonly DataInIssue[];\n\n constructor(issues: readonly DataInIssue[]) {\n super(\n ['Invalid step configuration', ...issues.map((issue) => `${issue.path || '/'}: ${issue.message}`)].join('\\n'),\n );\n this.name = 'DataInValidationError';\n this.issues = issues;\n }\n}\n\ninterface CompiledIssue {\n instancePath: string;\n message?: string;\n keyword: string;\n params: Record<string, unknown>;\n}\n\ninterface CompiledValidator {\n (value: unknown): { valid: boolean; errors: readonly CompiledIssue[] };\n}\n\nfunction configIssue(issue: CompiledIssue): DataInIssue {\n let path = issue.instancePath;\n if (issue.keyword === 'required' && typeof issue.params.missingProperty === 'string') {\n const property = issue.params.missingProperty.replaceAll('~', '~0').replaceAll('/', '~1');\n path += `/${property}`;\n }\n return { path, message: issue.message ?? 'Invalid value' };\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Copy only declared configuration fields, preserving opaque descendants.\n * Invalid object shapes remain unchanged so the compiled validator rejects them.\n */\nexport function projectObject(value: unknown, fields: readonly string[]): unknown {\n if (!isObject(value)) return value;\n // Match the previous parser's support for inherited declared fields.\n // eslint-disable-next-line unicorn/no-computed-property-existence-check\n return Object.fromEntries(fields.filter((field) => field in value).map((field) => [field, value[field]]));\n}\n\n/**\n * Preserve step merge-field normalization and the previous UTF-16 length limit.\n * Portable JSON Schema additionally checks its standard code-point length rules.\n */\nexport function normalizeString(value: unknown, path: string, maxLength?: number): unknown {\n if (typeof value !== 'string') return value;\n const normalized = value.trim();\n if (normalized === 'undefined' || normalized === 'null')\n throw new DataInValidationError([{ path, message: 'Unexpected undefined or null merge-field value' }]);\n if (maxLength !== undefined && normalized.length > maxLength)\n throw new DataInValidationError([{ path, message: `Must contain at most ${maxLength} UTF-16 code units` }]);\n return normalized;\n}\n\n/**\n * Record envelopes are copied, but arbitrary argument/context values stay live.\n * JSON Schema alone cannot distinguish a JavaScript record from a Map or class.\n */\nexport function copyRecord(value: unknown, path: string): unknown {\n if (value === undefined) return value;\n if (!isObject(value)) throw new DataInValidationError([{ path, message: 'Expected a record' }]);\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype)\n throw new DataInValidationError([{ path, message: 'Expected a record' }]);\n return Object.fromEntries(Object.entries(value));\n}\n\n/**\n * Normalize a fresh projection and validate it with AOT code.\n * No defaults, coercion, or input mutation occur.\n */\nexport function parseStepDataIn<T>(\n value: unknown,\n fields: readonly string[],\n validate: CompiledValidator,\n normalize: (data: Record<string, unknown>) => void,\n): T {\n const projected = projectObject(value, fields);\n if (isObject(projected)) normalize(projected);\n const result = validate(projected);\n if (!result.valid) throw new DataInValidationError(result.errors.map((issue) => configIssue(issue)));\n // T describes the validated configuration.\n return projected as T;\n}\n"],"mappings":"AAKA,IAAa,EAAb,cAA2C,KAAM,CAC/C,OAEA,YAAY,EAAgC,CAC1C,MACE,CAAC,6BAA8B,GAAG,EAAO,IAAK,GAAU,GAAG,EAAM,MAAQ,IAAI,IAAI,EAAM,SAAS,CAAC,CAAC,CAAC,KAAK;CAAI,CAC9G,EACA,KAAK,KAAO,wBACZ,KAAK,OAAS,CAChB,CACF,EAaA,SAAS,EAAY,EAAmC,CACtD,IAAI,EAAO,EAAM,aACjB,GAAI,EAAM,UAAY,YAAc,OAAO,EAAM,OAAO,iBAAoB,SAAU,CACpF,IAAM,EAAW,EAAM,OAAO,gBAAgB,WAAW,IAAK,IAAI,CAAC,CAAC,WAAW,IAAK,IAAI,EACxF,GAAQ,IAAI,GACd,CACA,MAAO,CAAE,OAAM,QAAS,EAAM,SAAW,eAAgB,CAC3D,CAEA,SAAS,EAAS,EAAkD,CAClE,OAAyB,OAAO,GAAU,YAAnC,GAA+C,CAAC,MAAM,QAAQ,CAAK,CAC5E,CAMA,SAAgB,EAAc,EAAgB,EAAoC,CAIhF,OAHK,EAAS,CAAK,EAGZ,OAAO,YAAY,EAAO,OAAQ,GAAU,KAAS,CAAK,CAAC,CAAC,IAAK,GAAU,CAAC,EAAO,EAAM,EAAM,CAAC,CAAC,EAH3E,CAI/B,CAMA,SAAgB,EAAgB,EAAgB,EAAc,EAA6B,CACzF,GAAI,OAAO,GAAU,SAAU,OAAO,EACtC,IAAM,EAAa,EAAM,KAAK,EAC9B,GAAI,IAAe,aAAe,IAAe,OAC/C,MAAM,IAAI,EAAsB,CAAC,CAAE,OAAM,QAAS,gDAAiD,CAAC,CAAC,EACvG,GAAI,IAAc,IAAA,IAAa,EAAW,OAAS,EACjD,MAAM,IAAI,EAAsB,CAAC,CAAE,OAAM,QAAS,wBAAwB,EAAU,mBAAoB,CAAC,CAAC,EAC5G,OAAO,CACT,CAMA,SAAgB,EAAW,EAAgB,EAAuB,CAChE,GAAI,IAAU,IAAA,GAAW,OAAO,EAChC,GAAI,CAAC,EAAS,CAAK,EAAG,MAAM,IAAI,EAAsB,CAAC,CAAE,OAAM,QAAS,mBAAoB,CAAC,CAAC,EAC9F,IAAM,EAAqB,OAAO,eAAe,CAAK,EACtD,GAAI,IAAc,MAAQ,IAAc,OAAO,UAC7C,MAAM,IAAI,EAAsB,CAAC,CAAE,OAAM,QAAS,mBAAoB,CAAC,CAAC,EAC1E,OAAO,OAAO,YAAY,OAAO,QAAQ,CAAK,CAAC,CACjD,CAMA,SAAgB,EACd,EACA,EACA,EACA,EACG,CACH,IAAM,EAAY,EAAc,EAAO,CAAM,EACzC,EAAS,CAAS,GAAG,EAAU,CAAS,EAC5C,IAAM,EAAS,EAAS,CAAS,EACjC,GAAI,CAAC,EAAO,MAAO,MAAM,IAAI,EAAsB,EAAO,OAAO,IAAK,GAAU,EAAY,CAAK,CAAC,CAAC,EAEnG,OAAO,CACT"}
@@ -0,0 +1,51 @@
1
+ import { TimeoutError } from "@onereach/flow-sdk/errors/timeout.js";
2
+ //#region src/errors/error-code.d.mts
3
+ type StepErrorCode = 'UNKNOWN' | 'STEP_LOGIC_ISSUE' | 'TIMEOUT' | 'VALIDATION' | 'NOT_FOUND' | 'CONFLICT' | 'CONFIGURATION' | 'SERVER_ERROR' | 'UNSUPPORTED';
4
+ //#endregion
5
+ //#region src/errors/error-filter.d.mts
6
+ interface StepErrorDetails {
7
+ code: StepErrorCode;
8
+ data?: unknown;
9
+ }
10
+ type StepErrorClass<E extends Error> = new (message: string, errorOrOptions?: Error | StepErrorDetails, options?: StepErrorDetails) => E;
11
+ /**
12
+ * Share Flow error classification while retaining each step's concrete error class.
13
+ */
14
+ declare function createErrorFilter<E extends Error>(StepError: StepErrorClass<E>): <P extends readonly AnyErrorClass[] = readonly [StepErrorClass<E>, typeof TimeoutError]>(error: unknown, options?: ErrorFilterOptions<P>) => InstancesOf<P> | E | TimeoutError;
15
+ type ErrorFilterOptions<P extends readonly AnyErrorClass[]> = {
16
+ /**
17
+ * Array of error classes that should not be wrapped
18
+ */
19
+ preserveErrors?: P;
20
+ /**
21
+ * Error message to use when message is unknown
22
+ */
23
+ unknownMessage?: string;
24
+ /**
25
+ * Error code to use when message is unknown
26
+ */
27
+ unknownCode?: StepErrorCode;
28
+ };
29
+ /**
30
+ * Any Error class
31
+ */
32
+ type AnyErrorClass<E extends Error = Error> = new (...arguments_: any[]) => E;
33
+ /**
34
+ * Turn a tuple/array of constructors into a union of their instance types.
35
+ */
36
+ type InstancesOf<Ctors extends readonly AnyErrorClass[]> = Ctors[number] extends AnyErrorClass<infer I> ? I : never;
37
+ //#endregion
38
+ //#region src/errors/framework-error.d.mts
39
+ interface FrameworkErrorDetails {
40
+ code: StepErrorCode;
41
+ message: string;
42
+ data: unknown;
43
+ }
44
+ /**
45
+ * Map known framework failures to Flow-facing diagnostics without changing their cause.
46
+ * Unrecognized errors remain the calling step's responsibility.
47
+ */
48
+ declare function frameworkErrorDetails(error: unknown): FrameworkErrorDetails | undefined;
49
+ //#endregion
50
+ export { AnyErrorClass, ErrorFilterOptions, InstancesOf, StepErrorClass, StepErrorCode, StepErrorDetails, createErrorFilter, frameworkErrorDetails };
51
+ //# sourceMappingURL=errors.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/errors/error-code.mts","../src/errors/error-filter.mts","../src/errors/framework-error.mts"],"mappings":";;KAAY;;;UCOK;EACf,MAAM;EACN;;KAGU,eAAe,UAAU,cACnC,iBACA,iBAAiB,QAAQ,kBACzB,UAAU,qBACP;;;;iBAKW,kBAAkB,UAAU,OAAO,WAAW,eAAe,MAE/C,mBAAmB,4BAAe,eAAA,WAAA,eAC5D,gBACA,UAAS,mBAAmB,OAC3B,YAAY,KAAK,IAAI;KAoEd,mBAAmB,mBAAmB;;;;EAIhD,iBAAiB;;;;EAIjB;;;;EAIA,cAAc;;;;;KAOJ,cAAc,UAAU,QAAQ,iBAAiB,sBAAsB;;;;KAKvE,YAAY,uBAAuB,mBAC7C,sBAAsB,oBAAoB,KAAK;;;UCrGvC;EACR,MAAM;EACN;EACA;;;;;;iBAOc,sBAAsB,iBAAiB"}
@@ -0,0 +1,4 @@
1
+ import{_ as e,a as t,f as n,g as r,h as i,i as a,l as o,m as s,o as c,p as l,r as u,s as d,t as f}from"./system-CZS-gIFs.mjs";import{t as p}from"./data-in-DT43edEv.mjs";import{TimeoutError as m}from"@onereach/flow-sdk/errors/timeout.js";function h(p){if(p instanceof a)return{code:`TIMEOUT`,message:p.message,data:{instanceId:p.instanceId,acquireTimeoutMs:p.acquireTimeoutMs}};if(p instanceof u)return{code:`CONFLICT`,message:p.message,data:{instanceId:p.instanceId}};if(p instanceof f){let e=p.issues.map(e=>`${e.path||`/`}: ${e.message}`);return{code:`VALIDATION`,message:[p.message,...e].join(`
2
+ `),data:{issues:p.issues}}}if(p instanceof c){let e=p.issues.map(e=>`/${(e.path??[]).map(e=>{let t=typeof e==`object`?e.key:e;return String(t).replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}).join(`/`)}: ${e.message}`);return{code:`VALIDATION`,message:[p.message,...e].join(`
3
+ `),data:{target:p.target,issues:p.issues}}}if(p instanceof r)return{code:`VALIDATION`,message:p.message,data:{path:p.path}};if(p instanceof t)return{code:`TIMEOUT`,message:p.message,data:{functionName:p.functionName,timeoutMs:p.timeoutMs}};if(p instanceof l)return{code:`NOT_FOUND`,message:p.message,data:{resource:p.resource}};if(p instanceof d)return{code:`NOT_FOUND`,message:p.message,data:{functionName:p.functionName}};if(p instanceof s||p instanceof i)return{code:`CONFLICT`,message:p.message,data:{expected:p.expected,actual:p.actual}};if(p instanceof o)return{code:`CONFIGURATION`,message:p.message,data:{option:p.option}};if(p instanceof n)return{code:`UNSUPPORTED`,message:p.message,data:{capability:p.capability}};if(p instanceof e)return{code:`UNSUPPORTED`,message:p.message,data:{concurrency:p.concurrency}}}function g(e){let t=[e,m];return function(n,r={}){let{preserveErrors:i=t,unknownMessage:a=`Unknown error`,unknownCode:o=`UNKNOWN`}=r;if(i?.some(e=>n instanceof e))return n;let s=h(n);if(s&&n instanceof Error)return s.code===`TIMEOUT`?new m(s.message,n,{code:s.code,data:s.data}):new e(s.message,n,{code:s.code,data:s.data});if(n instanceof p)return new e(n.message,n,{code:`VALIDATION`,data:{issues:n.issues}});if(typeof n==`string`)return new e(n,{code:`UNKNOWN`});if(n instanceof Error){if(n.message.includes(`Request timed out`))return new m(`Timeout`,n,{code:`TIMEOUT`});let t=n?.response?.data?.error?.message;return t==null?new e(a,n,{code:o}):new e(t,n,{code:`SERVER_ERROR`})}return new e(a,{code:o,data:n})}}export{g as createErrorFilter,h as frameworkErrorDetails};
4
+ //# sourceMappingURL=errors.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../src/errors/framework-error.mts","../src/errors/error-filter.mts"],"sourcesContent":["import {\n ContractValidationError,\n DriverCapabilityError,\n FunctionTimeoutError,\n NotFoundError,\n RevisionConflictError,\n SchemaValidationError,\n StateMachineConfigError,\n TemplateRevisionMismatchError,\n TemplateSnapshotError,\n UnknownFunctionError,\n UnsafeConcurrencyError,\n ExecutionLockTimeoutError,\n ExecutionLockLostError,\n} from '../system/index.ts';\n\nimport type { StepErrorCode } from './error-code.mts';\n\ninterface FrameworkErrorDetails {\n code: StepErrorCode;\n message: string;\n data: unknown;\n}\n\n/**\n * Map known framework failures to Flow-facing diagnostics without changing their cause.\n * Unrecognized errors remain the calling step's responsibility.\n */\nexport function frameworkErrorDetails(error: unknown): FrameworkErrorDetails | undefined {\n if (error instanceof ExecutionLockTimeoutError) {\n return {\n code: 'TIMEOUT',\n message: error.message,\n data: { instanceId: error.instanceId, acquireTimeoutMs: error.acquireTimeoutMs },\n };\n }\n if (error instanceof ExecutionLockLostError) {\n return { code: 'CONFLICT', message: error.message, data: { instanceId: error.instanceId } };\n }\n\n if (error instanceof ContractValidationError) {\n const details = error.issues.map((issue) => `${issue.path || '/'}: ${issue.message}`);\n return {\n code: 'VALIDATION',\n message: [error.message, ...details].join('\\n'),\n data: { issues: error.issues },\n };\n }\n\n if (error instanceof SchemaValidationError) {\n const details = error.issues.map((issue) => {\n const pointer = (issue.path ?? [])\n .map((segment) => {\n const key = typeof segment === 'object' ? segment.key : segment;\n return String(key).replaceAll('~', '~0').replaceAll('/', '~1');\n })\n .join('/');\n return `/${pointer}: ${issue.message}`;\n });\n return {\n code: 'VALIDATION',\n message: [error.message, ...details].join('\\n'),\n data: { target: error.target, issues: error.issues },\n };\n }\n\n if (error instanceof TemplateSnapshotError) {\n return { code: 'VALIDATION', message: error.message, data: { path: error.path } };\n }\n\n if (error instanceof FunctionTimeoutError) {\n return {\n code: 'TIMEOUT',\n message: error.message,\n data: { functionName: error.functionName, timeoutMs: error.timeoutMs },\n };\n }\n\n if (error instanceof NotFoundError) {\n return { code: 'NOT_FOUND', message: error.message, data: { resource: error.resource } };\n }\n\n if (error instanceof UnknownFunctionError) {\n return { code: 'NOT_FOUND', message: error.message, data: { functionName: error.functionName } };\n }\n\n if (error instanceof RevisionConflictError || error instanceof TemplateRevisionMismatchError) {\n return {\n code: 'CONFLICT',\n message: error.message,\n data: { expected: error.expected, actual: error.actual },\n };\n }\n\n if (error instanceof StateMachineConfigError) {\n return { code: 'CONFIGURATION', message: error.message, data: { option: error.option } };\n }\n\n if (error instanceof DriverCapabilityError) {\n return { code: 'UNSUPPORTED', message: error.message, data: { capability: error.capability } };\n }\n\n if (error instanceof UnsafeConcurrencyError) {\n return { code: 'UNSUPPORTED', message: error.message, data: { concurrency: error.concurrency } };\n }\n\n return undefined;\n}\n","import { TimeoutError } from '@onereach/flow-sdk/errors/timeout.js';\n\nimport { DataInValidationError } from '../configuration/data-in.mts';\n\nimport type { StepErrorCode } from './error-code.mts';\nimport { frameworkErrorDetails } from './framework-error.mts';\n\nexport interface StepErrorDetails {\n code: StepErrorCode;\n data?: unknown;\n}\n\nexport type StepErrorClass<E extends Error> = new (\n message: string,\n errorOrOptions?: Error | StepErrorDetails,\n options?: StepErrorDetails,\n) => E;\n\n/**\n * Share Flow error classification while retaining each step's concrete error class.\n */\nexport function createErrorFilter<E extends Error>(StepError: StepErrorClass<E>) {\n const defaultPreserveErrors = [StepError, TimeoutError] as const;\n return function errorFilter<P extends readonly AnyErrorClass[] = typeof defaultPreserveErrors>(\n error: unknown,\n options: ErrorFilterOptions<P> = {},\n ): InstancesOf<P> | E | TimeoutError {\n const {\n preserveErrors = defaultPreserveErrors,\n unknownMessage = 'Unknown error',\n unknownCode = 'UNKNOWN',\n } = options;\n\n // Preserve errors already classified by the step or SDK.\n if (preserveErrors?.some((ErrorClass) => error instanceof ErrorClass)) {\n return error as InstancesOf<P>;\n }\n\n const frameworkError = frameworkErrorDetails(error);\n if (frameworkError && error instanceof Error) {\n if (frameworkError.code === 'TIMEOUT') {\n return new TimeoutError(frameworkError.message, error, {\n code: frameworkError.code,\n data: frameworkError.data,\n });\n }\n return new StepError(frameworkError.message, error, {\n code: frameworkError.code,\n data: frameworkError.data,\n });\n }\n\n if (error instanceof DataInValidationError) {\n return new StepError(error.message, error, {\n code: 'VALIDATION',\n data: { issues: error.issues },\n });\n }\n\n // if error is a string assume it's an error message\n if (typeof error === 'string') {\n return new StepError(error, {\n code: '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: '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 StepError(responseErrorMessage, error, {\n code: 'SERVER_ERROR',\n });\n }\n\n return new StepError(unknownMessage, error, {\n code: unknownCode,\n });\n }\n\n // catch all for unknown errors\n return new StepError(unknownMessage, {\n code: unknownCode,\n data: error,\n });\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?: StepErrorCode;\n};\n\n/**\n * Any 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/**\n * Turn 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"],"mappings":"6OA4BA,SAAgB,EAAsB,EAAmD,CACvF,GAAI,aAAiB,EACnB,MAAO,CACL,KAAM,UACN,QAAS,EAAM,QACf,KAAM,CAAE,WAAY,EAAM,WAAY,iBAAkB,EAAM,gBAAiB,CACjF,EAEF,GAAI,aAAiB,EACnB,MAAO,CAAE,KAAM,WAAY,QAAS,EAAM,QAAS,KAAM,CAAE,WAAY,EAAM,UAAW,CAAE,EAG5F,GAAI,aAAiB,EAAyB,CAC5C,IAAM,EAAU,EAAM,OAAO,IAAK,GAAU,GAAG,EAAM,MAAQ,IAAI,IAAI,EAAM,SAAS,EACpF,MAAO,CACL,KAAM,aACN,QAAS,CAAC,EAAM,QAAS,GAAG,CAAO,CAAC,CAAC,KAAK;CAAI,EAC9C,KAAM,CAAE,OAAQ,EAAM,MAAO,CAC/B,CACF,CAEA,GAAI,aAAiB,EAAuB,CAC1C,IAAM,EAAU,EAAM,OAAO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AAM,cAAe,QAAS,EAAM,QAAS,KAAM,CAAE,YAAa,EAAM,WAAY,CAAE,CAInG,CCtFA,SAAgB,EAAmC,EAA8B,CAC/E,IAAM,EAAwB,CAAC,EAAW,CAAY,EACtD,OAAO,SACL,EACA,EAAiC,CAAC,EACC,CACnC,GAAM,CACJ,iBAAiB,EACjB,iBAAiB,gBACjB,cAAc,WACZ,EAGJ,GAAI,GAAgB,KAAM,GAAe,aAAiB,CAAU,EAClE,OAAO,EAGT,IAAM,EAAiB,EAAsB,CAAK,EAClD,GAAI,GAAkB,aAAiB,MAOrC,OANI,EAAe,OAAS,UACnB,IAAI,EAAa,EAAe,QAAS,EAAO,CACrD,KAAM,EAAe,KACrB,KAAM,EAAe,IACvB,CAAC,EAEI,IAAI,EAAU,EAAe,QAAS,EAAO,CAClD,KAAM,EAAe,KACrB,KAAM,EAAe,IACvB,CAAC,EAGH,GAAI,aAAiB,EACnB,OAAO,IAAI,EAAU,EAAM,QAAS,EAAO,CACzC,KAAM,aACN,KAAM,CAAE,OAAQ,EAAM,MAAO,CAC/B,CAAC,EAIH,GAAI,OAAO,GAAU,SACnB,OAAO,IAAI,EAAU,EAAO,CAC1B,KAAM,SACR,CAAC,EAGH,GAAI,aAAiB,MAAO,CAE1B,GAAI,EAAM,QAAQ,SAAS,mBAAmB,EAC5C,OAAO,IAAI,EAAa,UAAW,EAAO,CAAE,KAAM,SAAU,CAAC,EAK/D,IAAM,EAA4C,GAA0B,UAAU,MAAM,OAAO,QAOnG,OANI,GAAwB,KAMrB,IAAI,EAAU,EAAgB,EAAO,CAC1C,KAAM,CACR,CAAC,EAPQ,IAAI,EAAU,EAAsB,EAAO,CAChD,KAAM,cACR,CAAC,CAML,CAGA,OAAO,IAAI,EAAU,EAAgB,CACnC,KAAM,EACN,KAAM,CACR,CAAC,CACH,CACF"}
@@ -0,0 +1,136 @@
1
+ import { DriverCapabilityError, NotFoundError, RevisionConflictError, StateMachineInstanceDriver, StateMachineInstanceStore, StateTemplateDriver, StateTemplateStore, TemplateRevisionMismatchError, TemplateSnapshotError, UnsafeConcurrencyError } from "@onereach/state-machine-store";
2
+ import { BasicThreadService } from "@onereach/flow-sdk/services/basic.js";
3
+ import { ExecutionLockConfig, ExecutionLockOptions } from "@onereach/state-machine-coordination-onereach";
4
+ import { FunctionTimeoutError, RuntimeImplementationCompiler, StateMachineRuntime, UnknownFunctionError } from "@onereach/state-machine-runtime";
5
+ import { StateMachineService } from "@onereach/state-machine-service";
6
+ import { CachedStateTemplatePreparer, JsonSchemaValidatorCompiler, SchemaValidationError } from "@onereach/state-machine-validation";
7
+ import { ExecutionLockAcquireError, ExecutionLockLostError, ExecutionLockTimeoutError, StateMachineExecutionReference } from "@onereach/state-machine-coordination";
8
+ import { ContractValidationError } from "@onereach/state-machine-contracts";
9
+ import { CONFIG, ICacheFacade, IProcess, IThread } from "@onereach/flow-sdk/types/index.js";
10
+ export * from "@onereach/state-machine-store";
11
+ export * from "@onereach/state-machine-coordination-onereach";
12
+ export * from "@onereach/state-machine-driver-or-flow-mf";
13
+ export * from "@onereach/state-machine-json-schema-ajv";
14
+ export * from "@onereach/state-machine-runtime";
15
+ export * from "@onereach/state-machine-service";
16
+ export * from "@onereach/state-machine-contracts";
17
+ //#region src/system/types.d.ts
18
+ type InitializeStateMachineContext = Record<string, unknown>;
19
+ interface StateMachineProcessCache<TContext> {
20
+ readonly configuration: StateMachineSystemConfig;
21
+ readonly jsonSchemaCompiler: JsonSchemaValidatorCompiler;
22
+ readonly preparer: CachedStateTemplatePreparer;
23
+ readonly templateDriver: StateTemplateDriver;
24
+ readonly instanceDriver: StateMachineInstanceDriver;
25
+ readonly templates: StateTemplateStore;
26
+ readonly instances: StateMachineInstanceStore;
27
+ readonly runtime: StateMachineRuntime<TContext>;
28
+ readonly service: StateMachineService<TContext>;
29
+ }
30
+ /**
31
+ * Effective process-owned configuration. Engine/runtime policies and merge-field
32
+ * key layout are fixed by this integration version, not caller-selectable.
33
+ */
34
+ interface StateMachineSystemConfig {
35
+ readonly process: object;
36
+ readonly accountId: string;
37
+ readonly accountSlugId: string;
38
+ readonly cache: ICacheFacade;
39
+ readonly executionLock: Readonly<ExecutionLockConfig>;
40
+ readonly implementationCompiler: RuntimeImplementationCompiler | undefined;
41
+ }
42
+ type InitializeStateMachineOptions = {
43
+ /**
44
+ * Optional composition-owned backend compiler. Omission inherits an established
45
+ * compiler, or uses trusted JavaScript initially. Explicit identity conflicts
46
+ * are rejected rather than changing a running system.
47
+ */
48
+ implementationCompiler?: RuntimeImplementationCompiler;
49
+ /**
50
+ * Shared execution-lock wait, renewable lease, and retry policy.
51
+ * Explicit conflicts with an established process system are rejected.
52
+ */
53
+ executionLock?: ExecutionLockOptions;
54
+ /**
55
+ * Process-owned cache facade override, compared by object identity.
56
+ * Omission reuses an established system's facade, or the SDK Cache initially.
57
+ * A different explicit facade is rejected, not silently ignored.
58
+ */
59
+ cache?: ICacheFacade;
60
+ };
61
+ //#endregion
62
+ //#region src/system/state-machine.d.ts
63
+ declare class StateMachineThreadService<TConfig extends CONFIG, TContext> extends BasicThreadService<TConfig> {
64
+ readonly stateMachine: StateMachineService<TContext>;
65
+ /**
66
+ * Cache key for the state machine process cache.
67
+ * It represents the combination of used libraries and their versions.
68
+ */
69
+ readonly cacheKey = "sm:or-mf:json-schema-ajv:v6";
70
+ constructor(thread: IThread<TConfig>, options?: InitializeStateMachineOptions);
71
+ }
72
+ //#endregion
73
+ //#region src/system/system.d.ts
74
+ declare const STATE_MACHINE_PROCESS_CACHE_KEY = "sm:or-mf:json-schema-ajv:v6";
75
+ /**
76
+ * An explicit option or storage scope conflicts with the established system.
77
+ */
78
+ declare class StateMachineConfigError extends Error {
79
+ readonly option: 'cache' | 'storageScope' | 'executionLock' | 'implementationCompiler';
80
+ constructor(option: 'cache' | 'storageScope' | 'executionLock' | 'implementationCompiler');
81
+ }
82
+ /**
83
+ * Construct a complete process-owned system without publishing it to any cache.
84
+ * No thread or execution context is accepted or captured.
85
+ */
86
+ declare function createStateMachineSystem<TConfig extends CONFIG, TContext = Record<string, unknown>>(process: IProcess<TConfig>, options?: InitializeStateMachineOptions): StateMachineProcessCache<TContext>;
87
+ /**
88
+ * Retrieve the process system, or publish one only after construction succeeds.
89
+ * Omitted options inherit established values; explicit conflicts are rejected.
90
+ * Construction is synchronous, so no in-flight entry or cleanup is needed.
91
+ */
92
+ declare function getStateMachineSystem<TConfig extends CONFIG, TContext = Record<string, unknown>>(process: IProcess<TConfig>, options?: InitializeStateMachineOptions): StateMachineProcessCache<TContext>;
93
+ //#endregion
94
+ //#region src/functions.d.ts
95
+ /**
96
+ * Execute a function through the state-machine service.
97
+ *
98
+ * @param input - Optional function input. Omission or `undefined` creates a fresh
99
+ * empty object. Explicit values, including `null`, are preserved. Input must
100
+ * satisfy the function's schema, so functions requiring fields need explicit input.
101
+ * @param context - Optional per-call execution context. Omission or `undefined`
102
+ * creates a fresh empty object; context is never inherited from initialization.
103
+ * @returns A promise for the function output, not the service result envelope.
104
+ */
105
+ type CachedStateMachineFunction = (input?: unknown, context?: InitializeStateMachineContext) => Promise<unknown>;
106
+ /**
107
+ * Consumer-facing convenience lookup exposed at `process.cache.stateMachines`.
108
+ * This is not an execution authorization or agent-routing boundary.
109
+ */
110
+ interface StateMachineFunctions {
111
+ /**
112
+ * Return a reusable lazy callable bound to the supplied instance ID.
113
+ *
114
+ * @param instanceId - Persisted instance ID. It need not be initialized by this flow.
115
+ * @param functionName - Function name, validated against the resolved template on invocation.
116
+ * @returns An asynchronous callable whose optional `input` and `context` default
117
+ * to fresh empty objects on each invocation. Calls return function output only.
118
+ * Previously retrieved functions keep their original instance binding after
119
+ * reinitialization and always execute against its current persisted state.
120
+ * Wrapper identity is not stable across lookups; runtime preparation is cached
121
+ * by the framework service rather than by these convenience callables.
122
+ * @throws If this flow has not yet enabled the cache convenience API by passing
123
+ * through an initialization step. Missing instances and unknown function names
124
+ * reject asynchronously during service execution.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * const serialize = process.cache.stateMachines.getFunction(instanceId, 'serialize_state');
129
+ * const state = await serialize();
130
+ * ```
131
+ */
132
+ getFunction(instanceId: string, functionName: string): CachedStateMachineFunction;
133
+ }
134
+ //#endregion
135
+ export { type CachedStateMachineFunction, ContractValidationError, DriverCapabilityError, ExecutionLockAcquireError, ExecutionLockLostError, ExecutionLockTimeoutError, FunctionTimeoutError, type InitializeStateMachineContext, type InitializeStateMachineOptions, NotFoundError, RevisionConflictError, STATE_MACHINE_PROCESS_CACHE_KEY, SchemaValidationError, StateMachineConfigError, type StateMachineExecutionReference, type StateMachineFunctions, type StateMachineProcessCache, type StateMachineSystemConfig, StateMachineThreadService, TemplateRevisionMismatchError, TemplateSnapshotError, UnknownFunctionError, UnsafeConcurrencyError, createStateMachineSystem, getStateMachineSystem };
136
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/system/types.ts","../src/system/state-machine.ts","../src/system/system.ts","../src/functions.ts"],"mappings":";;;;;;;;;;;;;;;;;KAYY,gCAAgC;UAE3B,yBAAyB;WAC/B,eAAe;WACf,oBAAoB;WACpB,UAAU;WACV,gBAAgB;WAChB,gBAAgB;WAChB,WAAW;WACX,WAAW;WACX,SAAS,oBAAoB;WAC7B,SAAS,oBAAoB;;;;;;UAOvB;WACN;WACA;WACA;WACA,OAAO;WACP,eAAe,SAAS;WACxB,wBAAwB;;KAGvB;;;;;;EAMV,yBAAyB;;;;;EAMzB,gBAAgB;;;;;;EAOhB,QAAQ;;;;cCnDG,0BAA0B,gBAAgB,QAAQ,kBAAkB,mBAAmB;WAClF,cAAc,oBAAoB;;;;;WAMlC;EAEJ,YAAA,QAAQ,QAAQ,UAAU,UAAU;;;;cCCrC;;;;cAKA,gCAAgC;WAC3B;EAEJ,YAAA;;;;;;iBA8BE,yBAAyB,gBAAgB,QAAQ,WAAW,yBAC1E,SAAS,SAAS,UAClB,UAAU,gCACT,yBAAyB;;;;;;iBAsDZ,sBAAsB,gBAAgB,QAAQ,WAAW,yBACvE,SAAS,SAAS,UAClB,UAAU,gCACT,yBAAyB;;;;;;;;;;;;;KCvGhB,8BAA8B,iBAAiB,UAAU,kCAAkC;;;;;UAMtF;;;;;;;;;;;;;;;;;;;;;;EAsBf,YAAY,oBAAoB,uBAAuB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./system-CZS-gIFs.mjs";import{BasicThreadService as _}from"@onereach/flow-sdk/services/basic.js";var v=class extends _{stateMachine;cacheKey=n;constructor(e,t){super(e),this.stateMachine=r(this.process,t).service}};export{h as ContractValidationError,i as DriverCapabilityError,u as ExecutionLockAcquireError,p as ExecutionLockLostError,s as ExecutionLockTimeoutError,t as FunctionTimeoutError,f as NotFoundError,l as RevisionConflictError,n as STATE_MACHINE_PROCESS_CACHE_KEY,d as SchemaValidationError,c as StateMachineConfigError,v as StateMachineThreadService,o as TemplateRevisionMismatchError,a as TemplateSnapshotError,m as UnknownFunctionError,e as UnsafeConcurrencyError,g as createStateMachineSystem,r as getStateMachineSystem};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/system/state-machine.ts"],"sourcesContent":["import { BasicThreadService } from '@onereach/flow-sdk/services/basic.js';\nimport type { IThread, CONFIG } from '@onereach/flow-sdk/types/index.js';\nimport type { StateMachineService } from '@onereach/state-machine-service';\n\nimport { getStateMachineSystem, STATE_MACHINE_PROCESS_CACHE_KEY } from './system.ts';\nimport type { InitializeStateMachineOptions } from './types.ts';\n\nexport class StateMachineThreadService<TConfig extends CONFIG, TContext> extends BasicThreadService<TConfig> {\n public readonly stateMachine: StateMachineService<TContext>;\n\n /**\n * Cache key for the state machine process cache.\n * It represents the combination of used libraries and their versions.\n */\n public readonly cacheKey = STATE_MACHINE_PROCESS_CACHE_KEY;\n\n constructor(thread: IThread<TConfig>, options?: InitializeStateMachineOptions) {\n super(thread);\n this.stateMachine = getStateMachineSystem<TConfig, TContext>(this.process, options).service;\n }\n}\n"],"mappings":"oOAOA,IAAa,EAAb,cAAiF,CAA4B,CAC3G,aAMA,SAA2B,EAE3B,YAAY,EAA0B,EAAyC,CAC7E,MAAM,CAAM,EACZ,KAAK,aAAe,EAAyC,KAAK,QAAS,CAAO,CAAC,CAAC,OACtF,CACF"}
@@ -0,0 +1,76 @@
1
+ import { ExecuteStateMachineFunctionOptions, ManagedExecutionResult } from "@onereach/state-machine-service";
2
+ import { ExecuteStateMachineFunctionRequest } from "@onereach/state-machine-contracts";
3
+ import { CONFIG, IThread } from "@onereach/flow-sdk/types/index.js";
4
+ //#region src/notifications/index.d.ts
5
+ type ChangeSource = 'local' | 'remote';
6
+ interface StateChangeIdentity {
7
+ instanceId: string;
8
+ templateId: string;
9
+ }
10
+ interface NotificationFailure {
11
+ /**
12
+ * `policy` denotes a failure resolving notification routing after commit.
13
+ */
14
+ channel: ChangeSource | 'policy';
15
+ message: string;
16
+ }
17
+ interface StateChangePublicationOptions {
18
+ localStepId?: string;
19
+ localStepIds?: readonly string[];
20
+ remote?: boolean;
21
+ /**
22
+ * Skip absent or ended local listeners instead of reporting delivery failures.
23
+ * Defaults to false for callers explicitly requesting delivery to a selected step.
24
+ */
25
+ skipInactiveLocalTargets?: boolean;
26
+ }
27
+ declare const stateChangeListenerClassId = "cng_lnr";
28
+ declare const localStateChangeEvent = "st_cgd";
29
+ /**
30
+ * Keep SDK thread addressing private to the shared Flow notification boundary.
31
+ */
32
+ declare function stateChangeListenerThreadId(stepId: string): string;
33
+ /**
34
+ * Encode identity segments independently so identifiers containing slashes cannot collide.
35
+ * Account/topic authorization and scope remain owned by the Flow SDK.
36
+ */
37
+ declare function remoteStateChangeEvent(identity: StateChangeIdentity): `sm/${string}/${string}`;
38
+ /**
39
+ * Publish best-effort invalidation hints after persistence. Each channel is
40
+ * attempted independently; failures are returned, never retried as mutations.
41
+ */
42
+ declare function publishStateChange<T extends CONFIG>(thread: IThread<T>, identity: StateChangeIdentity, options: StateChangePublicationOptions): Promise<NotificationFailure[]>;
43
+ /**
44
+ * Execute once through the service, then publish best-effort hints only for a
45
+ * committed mutation. Execution errors propagate without publication or retries.
46
+ *
47
+ * @param notifications - Explicit publication policy, or a callback evaluated
48
+ * after a mutation commits to resolve current notification recipients.
49
+ * @returns The unchanged service result and any serializable publication failures,
50
+ * including `channel: 'policy'` if routing resolution or publication setup throws.
51
+ */
52
+ declare function executeStateMachineFunction<TConfig extends CONFIG, TContext, TOutput = unknown>(thread: IThread<TConfig>, service: {
53
+ execute: (request: ExecuteStateMachineFunctionRequest, context: TContext, options?: ExecuteStateMachineFunctionOptions) => Promise<ManagedExecutionResult<TOutput>>;
54
+ }, request: ExecuteStateMachineFunctionRequest, context: TContext, notifications?: StateChangePublicationOptions | (() => StateChangePublicationOptions), executionOptions?: ExecuteStateMachineFunctionOptions): Promise<{
55
+ result: ManagedExecutionResult<TOutput>;
56
+ notificationFailures: NotificationFailure[];
57
+ }>;
58
+ interface RefreshHint {
59
+ callbackSource?: ChangeSource;
60
+ }
61
+ /**
62
+ * Serialize refreshes with one pending invalidation, not a history of snapshots.
63
+ * The most recent eligible hint selects a callback source; disabled sources
64
+ * still invalidate state but cannot erase a pending eligible callback request.
65
+ */
66
+ declare class LatestStateRefresh {
67
+ private pending?;
68
+ private running?;
69
+ private readonly refresh;
70
+ constructor(refresh: (hint: RefreshHint) => Promise<void>);
71
+ private drain;
72
+ request(source?: ChangeSource): Promise<void>;
73
+ }
74
+ //#endregion
75
+ export { ChangeSource, LatestStateRefresh, NotificationFailure, RefreshHint, StateChangeIdentity, StateChangePublicationOptions, executeStateMachineFunction, localStateChangeEvent, publishStateChange, remoteStateChangeEvent, stateChangeListenerClassId, stateChangeListenerThreadId };
76
+ //# sourceMappingURL=notifications.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications.d.mts","names":[],"sources":["../src/notifications/index.ts"],"mappings":";;;;KAIY;UAEK;EACf;EACA;;UAGe;;;;EAIf,SAAS;EACT;;UAGe;EACf;EACA;EACA;;;;;EAKA;;cAGW;cACA;;;;iBAKG,4BAA4B;;;;;iBAQ5B,uBAAuB,UAAU;;;;;iBA6B3B,mBAAmB,UAAU,QACjD,QAAQ,QAAQ,IAChB,UAAU,qBACV,SAAS,gCACR,QAAQ;;;;;;;;;;iBAwCW,4BAA4B,gBAAgB,QAAQ,UAAU,mBAClF,QAAQ,QAAQ,UAChB;EACE,UACE,SAAS,oCACT,SAAS,UACT,UAAU,uCACP,QAAQ,uBAAuB;GAEtC,SAAS,oCACT,SAAS,UACT,gBAAe,uCAAuC,gCACtD,mBAAmB,qCAClB;EAAU,QAAQ,uBAAuB;EAAU,sBAAsB;;UAc3D;EACf,iBAAiB;;;;;;;cAQN;UACH;UACA;mBAES;EAEL,YAAA,UAAU,MAAM,gBAAgB;UAI9B;EAeP,QAAQ,SAAS,eAAe"}
@@ -0,0 +1,2 @@
1
+ const e=`cng_lnr`,t=`st_cgd`;function n(t){return`sm_mgr_${e}_${t}`}function r(e){return`sm/${encodeURIComponent(e.templateId)}/${encodeURIComponent(e.instanceId)}`}function i(e,t,n,r){let i=`Notification failed`;try{let e=r instanceof Error?r.message:r;typeof e==`string`&&(i=e)}catch{}try{e.log.WARN?.(`State mutation committed, but notification failed`,{channel:n,identity:t,error:r})}catch{}return{channel:n,message:i}}async function a(e,a,o){let{localStepId:s,localStepIds:c,remote:l,skipInactiveLocalTargets:u}=o,d=new Set(c);s!==void 0&&d.add(s);let f=[],p=async(t,n)=>{try{let e=await n();if(e instanceof Error)throw e}catch(n){f.push(i(e,a,t,n))}};for(let r of d){let i=n(r);await p(`local`,()=>{let n=e.process.getThread(i);if(!n||n.ended){if(u)return;throw Error(`State change listener is not active`)}return e.process.enqueueAndRun({name:t,thread:i,params:a})})}return l&&await p(`remote`,()=>e.emitAsync({name:r(a),params:a})),f}async function o(e,t,n,r,o={},s){let c=await(s===void 0?t.execute(n,r):t.execute(n,r,s));if(c.kind===`query`)return{result:c,notificationFailures:[]};let l={instanceId:c.instance.instance.id,templateId:c.instance.instance.template.id};try{return{result:c,notificationFailures:await a(e,l,typeof o==`function`?o():o)}}catch(t){return{result:c,notificationFailures:[i(e,l,`policy`,t)]}}}var s=class{pending;running;refresh;constructor(e){this.refresh=e}async drain(){await Promise.resolve();try{for(;this.pending;){let e=this.pending;this.pending=void 0,await this.refresh(e)}}finally{this.running=void 0}}request(e){return this.pending={callbackSource:e??this.pending?.callbackSource},this.running??=this.drain(),this.running}};export{s as LatestStateRefresh,o as executeStateMachineFunction,t as localStateChangeEvent,a as publishStateChange,r as remoteStateChangeEvent,e as stateChangeListenerClassId,n as stateChangeListenerThreadId};
2
+ //# sourceMappingURL=notifications.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications.mjs","names":[],"sources":["../src/notifications/index.ts"],"sourcesContent":["import type { CONFIG, IThread } from '@onereach/flow-sdk/types/index.js';\nimport type { ExecuteStateMachineFunctionRequest } from '@onereach/state-machine-contracts';\nimport type { ExecuteStateMachineFunctionOptions, ManagedExecutionResult } from '@onereach/state-machine-service';\n\nexport type ChangeSource = 'local' | 'remote';\n\nexport interface StateChangeIdentity {\n instanceId: string;\n templateId: string;\n}\n\nexport interface NotificationFailure {\n /**\n * `policy` denotes a failure resolving notification routing after commit.\n */\n channel: ChangeSource | 'policy';\n message: string;\n}\n\nexport interface StateChangePublicationOptions {\n localStepId?: string;\n localStepIds?: readonly string[];\n remote?: boolean;\n /**\n * Skip absent or ended local listeners instead of reporting delivery failures.\n * Defaults to false for callers explicitly requesting delivery to a selected step.\n */\n skipInactiveLocalTargets?: boolean;\n}\n\nexport const stateChangeListenerClassId = 'cng_lnr';\nexport const localStateChangeEvent = 'st_cgd';\n\n/**\n * Keep SDK thread addressing private to the shared Flow notification boundary.\n */\nexport function stateChangeListenerThreadId(stepId: string): string {\n return `sm_mgr_${stateChangeListenerClassId}_${stepId}`;\n}\n\n/**\n * Encode identity segments independently so identifiers containing slashes cannot collide.\n * Account/topic authorization and scope remain owned by the Flow SDK.\n */\nexport function remoteStateChangeEvent(identity: StateChangeIdentity): `sm/${string}/${string}` {\n return `sm/${encodeURIComponent(identity.templateId)}/${encodeURIComponent(identity.instanceId)}`;\n}\n\nfunction reportNotificationFailure<T extends CONFIG>(\n thread: IThread<T>,\n identity: StateChangeIdentity,\n channel: NotificationFailure['channel'],\n error: unknown,\n): NotificationFailure {\n let message = 'Notification failed';\n try {\n const detail = error instanceof Error ? error.message : error;\n if (typeof detail === 'string') message = detail;\n } catch {\n // Even a thrown value with an unreadable message must remain best-effort.\n }\n try {\n thread.log.WARN?.('State mutation committed, but notification failed', { channel, identity, error });\n } catch {\n // Diagnostics must not replace a committed mutation result.\n }\n return { channel, message };\n}\n\n/**\n * Publish best-effort invalidation hints after persistence. Each channel is\n * attempted independently; failures are returned, never retried as mutations.\n */\nexport async function publishStateChange<T extends CONFIG>(\n thread: IThread<T>,\n identity: StateChangeIdentity,\n options: StateChangePublicationOptions,\n): Promise<NotificationFailure[]> {\n // Resolve all policy getters and recipients before any delivery can run.\n const { localStepId, localStepIds: recipients, remote, skipInactiveLocalTargets } = options;\n const localStepIds = new Set(recipients);\n if (localStepId !== undefined) localStepIds.add(localStepId);\n const failures: NotificationFailure[] = [];\n const attempt = async (channel: ChangeSource, publish: () => unknown): Promise<void> => {\n try {\n const result = await publish();\n if (result instanceof Error) throw result;\n } catch (error) {\n failures.push(reportNotificationFailure(thread, identity, channel, error));\n }\n };\n for (const stepId of localStepIds) {\n const listenerId = stateChangeListenerThreadId(stepId);\n await attempt('local', () => {\n const listener = thread.process.getThread(listenerId);\n if (!listener || listener.ended) {\n if (skipInactiveLocalTargets) return;\n throw new Error('State change listener is not active');\n }\n return thread.process.enqueueAndRun({ name: localStateChangeEvent, thread: listenerId, params: identity });\n });\n }\n if (remote) {\n await attempt('remote', () => thread.emitAsync({ name: remoteStateChangeEvent(identity), params: identity }));\n }\n return failures;\n}\n\n/**\n * Execute once through the service, then publish best-effort hints only for a\n * committed mutation. Execution errors propagate without publication or retries.\n *\n * @param notifications - Explicit publication policy, or a callback evaluated\n * after a mutation commits to resolve current notification recipients.\n * @returns The unchanged service result and any serializable publication failures,\n * including `channel: 'policy'` if routing resolution or publication setup throws.\n */\nexport async function executeStateMachineFunction<TConfig extends CONFIG, TContext, TOutput = unknown>(\n thread: IThread<TConfig>,\n service: {\n execute: (\n request: ExecuteStateMachineFunctionRequest,\n context: TContext,\n options?: ExecuteStateMachineFunctionOptions,\n ) => Promise<ManagedExecutionResult<TOutput>>;\n },\n request: ExecuteStateMachineFunctionRequest,\n context: TContext,\n notifications: StateChangePublicationOptions | (() => StateChangePublicationOptions) = {},\n executionOptions?: ExecuteStateMachineFunctionOptions,\n): Promise<{ result: ManagedExecutionResult<TOutput>; notificationFailures: NotificationFailure[] }> {\n const result = await (executionOptions === undefined\n ? service.execute(request, context)\n : service.execute(request, context, executionOptions));\n if (result.kind === 'query') return { result, notificationFailures: [] };\n const identity = { instanceId: result.instance.instance.id, templateId: result.instance.instance.template.id };\n try {\n const policy = typeof notifications === 'function' ? notifications() : notifications;\n return { result, notificationFailures: await publishStateChange(thread, identity, policy) };\n } catch (error) {\n return { result, notificationFailures: [reportNotificationFailure(thread, identity, 'policy', error)] };\n }\n}\n\nexport interface RefreshHint {\n callbackSource?: ChangeSource;\n}\n\n/**\n * Serialize refreshes with one pending invalidation, not a history of snapshots.\n * The most recent eligible hint selects a callback source; disabled sources\n * still invalidate state but cannot erase a pending eligible callback request.\n */\nexport class LatestStateRefresh {\n private pending?: RefreshHint;\n private running?: Promise<void>;\n\n private readonly refresh: (hint: RefreshHint) => Promise<void>;\n\n constructor(refresh: (hint: RefreshHint) => Promise<void>) {\n this.refresh = refresh;\n }\n\n private async drain(): Promise<void> {\n // Yield before starting so synchronous loader failures cannot leave a stale\n // rejected promise assigned after the finally block clears it.\n await Promise.resolve();\n try {\n while (this.pending) {\n const hint = this.pending;\n this.pending = undefined;\n await this.refresh(hint);\n }\n } finally {\n this.running = undefined;\n }\n }\n\n public request(source?: ChangeSource): Promise<void> {\n this.pending = { callbackSource: source ?? this.pending?.callbackSource };\n this.running ??= this.drain();\n return this.running;\n }\n}\n"],"mappings":"AA8BA,MAAa,EAA6B,UAC7B,EAAwB,SAKrC,SAAgB,EAA4B,EAAwB,CAClE,MAAO,UAAU,EAA2B,GAAG,GACjD,CAMA,SAAgB,EAAuB,EAAyD,CAC9F,MAAO,MAAM,mBAAmB,EAAS,UAAU,EAAE,GAAG,mBAAmB,EAAS,UAAU,GAChG,CAEA,SAAS,EACP,EACA,EACA,EACA,EACqB,CACrB,IAAI,EAAU,sBACd,GAAI,CACF,IAAM,EAAS,aAAiB,MAAQ,EAAM,QAAU,EACpD,OAAO,GAAW,WAAU,EAAU,EAC5C,MAAQ,CAER,CACA,GAAI,CACF,EAAO,IAAI,OAAO,oDAAqD,CAAE,UAAS,WAAU,OAAM,CAAC,CACrG,MAAQ,CAER,CACA,MAAO,CAAE,UAAS,SAAQ,CAC5B,CAMA,eAAsB,EACpB,EACA,EACA,EACgC,CAEhC,GAAM,CAAE,cAAa,aAAc,EAAY,SAAQ,4BAA6B,EAC9E,EAAe,IAAI,IAAI,CAAU,EACnC,IAAgB,IAAA,IAAW,EAAa,IAAI,CAAW,EAC3D,IAAM,EAAkC,CAAC,EACnC,EAAU,MAAO,EAAuB,IAA0C,CACtF,GAAI,CACF,IAAM,EAAS,MAAM,EAAQ,EAC7B,GAAI,aAAkB,MAAO,MAAM,CACrC,OAAS,EAAO,CACd,EAAS,KAAK,EAA0B,EAAQ,EAAU,EAAS,CAAK,CAAC,CAC3E,CACF,EACA,IAAK,IAAM,KAAU,EAAc,CACjC,IAAM,EAAa,EAA4B,CAAM,EACrD,MAAM,EAAQ,YAAe,CAC3B,IAAM,EAAW,EAAO,QAAQ,UAAU,CAAU,EACpD,GAAI,CAAC,GAAY,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E,KAAK,UAAY,KAAK,MAAM,EACrB,KAAK,OACd,CACF"}
@@ -0,0 +1,2 @@
1
+ import{DriverCapabilityError as e,NotFoundError as t,RevisionConflictError as n,StateMachineInstanceStore as r,StateTemplateStore as i,TemplateRevisionMismatchError as a,TemplateSnapshotError as o,UnsafeConcurrencyError as s}from"@onereach/state-machine-store";import{Cache as c}from"@onereach/flow-sdk/services/cache.js";import{OneReachExecutionLocks as l,normalizeExecutionLockOptions as u}from"@onereach/state-machine-coordination-onereach";import{OrFlowStorageStateInstanceDriver as d,OrFlowStorageStateTemplateDriver as f,getInstanceKey as p}from"@onereach/state-machine-driver-or-flow-mf";import{AjvJsonSchemaValidatorCompiler as m}from"@onereach/state-machine-json-schema-ajv";import{FunctionTimeoutError as h,StateMachineRuntime as g,UnknownFunctionError as _}from"@onereach/state-machine-runtime";import{StateMachineService as v}from"@onereach/state-machine-service";import{CachedStateTemplatePreparer as y,SchemaValidationError as b}from"@onereach/state-machine-validation";import{ExecutionLockAcquireError as x,ExecutionLockLostError as S,ExecutionLockTimeoutError as C}from"@onereach/state-machine-coordination";import{ContractValidationError as w}from"@onereach/state-machine-contracts";const T=`sm:or-mf:json-schema-ajv:v6`;var E=class extends Error{option;constructor(e){super(`State machine process configuration conflicts with the established system: ${e}`),this.name=`StateMachineConfigError`,this.option=e}};function D(e,t,n){return Object.freeze({process:e,accountId:e.config.accountId,accountSlugId:e.config.accountSlugId,cache:t?.cache??n?.cache??c,implementationCompiler:t?.implementationCompiler??n?.implementationCompiler,executionLock:u({acquireTimeoutMs:t?.executionLock?.acquireTimeoutMs??n?.executionLock.acquireTimeoutMs,leaseDurationMs:t?.executionLock?.leaseDurationMs??n?.executionLock.leaseDurationMs,retryDelayMs:t?.executionLock?.retryDelayMs??n?.executionLock.retryDelayMs})})}function O(e,t){return k(e,D(e,t))}function k(e,t){let n=new m,a=new y(n),o=new f(e,{cache:t.cache}),s=new d(e,{cache:t.cache}),c=new i(o,a),u=new r(s,c),h=new g({implementationCompiler:t.implementationCompiler}),_=new v(u,h,{executionLocks:new l(t.cache,{accountSlugId:t.accountSlugId,accountId:t.accountId,instanceKey:p},t.executionLock,{onReleaseFailure:t=>{e.log.WARN?.(`State-machine execution lock release failed; operation outcome unchanged`,t)},onRetentionChange:t=>{t.phase===`settled`?e.log.INFO?.(`State-machine retained execution settled`,t):e.log.WARN?.(`State-machine execution remains retained after caller completion`,t)}})});return Object.freeze({configuration:t,jsonSchemaCompiler:n,preparer:a,templateDriver:o,instanceDriver:s,templates:c,instances:u,runtime:h,service:_})}function A(e,t){let n=e.cache[T],r=D(e,t,n?.configuration);if(n){let t=n.configuration;if(t.process!==e||t.accountId!==r.accountId||t.accountSlugId!==r.accountSlugId)throw new E(`storageScope`);if(t.cache!==r.cache)throw new E(`cache`);if(t.implementationCompiler!==r.implementationCompiler)throw new E(`implementationCompiler`);if(Object.entries(t.executionLock).some(([e,t])=>r.executionLock[e]!==t))throw new E(`executionLock`);return n}let i=k(e,r);return e.cache[T]=i,i}export{s as _,h as a,T as c,A as d,e as f,o as g,a as h,C as i,E as l,n as m,x as n,b as o,t as p,S as r,_ as s,w as t,O as u};
2
+ //# sourceMappingURL=system-CZS-gIFs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"system-CZS-gIFs.mjs","names":[],"sources":["../src/system/system.ts"],"sourcesContent":["import { Cache } from '@onereach/flow-sdk/services/cache.js';\nimport type { CONFIG, IProcess } from '@onereach/flow-sdk/types/index.js';\nimport { normalizeExecutionLockOptions, OneReachExecutionLocks } from '@onereach/state-machine-coordination-onereach';\nimport {\n OrFlowStorageStateInstanceDriver,\n OrFlowStorageStateTemplateDriver,\n getInstanceKey,\n} from '@onereach/state-machine-driver-or-flow-mf';\nimport { AjvJsonSchemaValidatorCompiler } from '@onereach/state-machine-json-schema-ajv';\nimport { StateMachineRuntime } from '@onereach/state-machine-runtime';\nimport { StateMachineService } from '@onereach/state-machine-service';\nimport { StateMachineInstanceStore, StateTemplateStore } from '@onereach/state-machine-store';\nimport { CachedStateTemplatePreparer } from '@onereach/state-machine-validation';\n\nimport type { InitializeStateMachineOptions, StateMachineProcessCache, StateMachineSystemConfig } from './types.ts';\n\n// A new namespace prevents legacy partial process entries from being reused.\nexport const STATE_MACHINE_PROCESS_CACHE_KEY = 'sm:or-mf:json-schema-ajv:v6';\n\n/**\n * An explicit option or storage scope conflicts with the established system.\n */\nexport class StateMachineConfigError extends Error {\n public readonly option: 'cache' | 'storageScope' | 'executionLock' | 'implementationCompiler';\n\n constructor(option: 'cache' | 'storageScope' | 'executionLock' | 'implementationCompiler') {\n super(`State machine process configuration conflicts with the established system: ${option}`);\n this.name = 'StateMachineConfigError';\n this.option = option;\n }\n}\n\nfunction normalizeConfig<TConfig extends CONFIG>(\n process: IProcess<TConfig>,\n options?: InitializeStateMachineOptions,\n established?: StateMachineSystemConfig,\n): StateMachineSystemConfig {\n return Object.freeze({\n process,\n accountId: process.config.accountId,\n accountSlugId: process.config.accountSlugId,\n cache: options?.cache ?? established?.cache ?? Cache,\n implementationCompiler: options?.implementationCompiler ?? established?.implementationCompiler,\n executionLock: normalizeExecutionLockOptions({\n acquireTimeoutMs: options?.executionLock?.acquireTimeoutMs ?? established?.executionLock.acquireTimeoutMs,\n leaseDurationMs: options?.executionLock?.leaseDurationMs ?? established?.executionLock.leaseDurationMs,\n retryDelayMs: options?.executionLock?.retryDelayMs ?? established?.executionLock.retryDelayMs,\n }),\n });\n}\n\n/**\n * Construct a complete process-owned system without publishing it to any cache.\n * No thread or execution context is accepted or captured.\n */\nexport function createStateMachineSystem<TConfig extends CONFIG, TContext = Record<string, unknown>>(\n process: IProcess<TConfig>,\n options?: InitializeStateMachineOptions,\n): StateMachineProcessCache<TContext> {\n return constructSystem(process, normalizeConfig(process, options));\n}\n\nfunction constructSystem<TConfig extends CONFIG, TContext>(\n process: IProcess<TConfig>,\n config: StateMachineSystemConfig,\n): StateMachineProcessCache<TContext> {\n const jsonSchemaCompiler = new AjvJsonSchemaValidatorCompiler();\n const preparer = new CachedStateTemplatePreparer(jsonSchemaCompiler);\n const templateDriver = new OrFlowStorageStateTemplateDriver(process, { cache: config.cache });\n const instanceDriver = new OrFlowStorageStateInstanceDriver(process, {\n cache: config.cache,\n });\n const templates = new StateTemplateStore(templateDriver, preparer);\n const instances = new StateMachineInstanceStore(instanceDriver, templates);\n const runtime = new StateMachineRuntime<TContext>({ implementationCompiler: config.implementationCompiler });\n const service = new StateMachineService(instances, runtime, {\n executionLocks: new OneReachExecutionLocks(\n config.cache,\n { accountSlugId: config.accountSlugId, accountId: config.accountId, instanceKey: getInstanceKey },\n config.executionLock,\n {\n onReleaseFailure: (failure) => {\n process.log.WARN?.('State-machine execution lock release failed; operation outcome unchanged', failure);\n },\n onRetentionChange: (event) => {\n if (event.phase === 'settled') {\n process.log.INFO?.('State-machine retained execution settled', event);\n } else {\n process.log.WARN?.('State-machine execution remains retained after caller completion', event);\n }\n },\n },\n ),\n });\n return Object.freeze({\n configuration: config,\n jsonSchemaCompiler,\n preparer,\n templateDriver,\n instanceDriver,\n templates,\n instances,\n runtime,\n service,\n });\n}\n\n/**\n * Retrieve the process system, or publish one only after construction succeeds.\n * Omitted options inherit established values; explicit conflicts are rejected.\n * Construction is synchronous, so no in-flight entry or cleanup is needed.\n */\nexport function getStateMachineSystem<TConfig extends CONFIG, TContext = Record<string, unknown>>(\n process: IProcess<TConfig>,\n options?: InitializeStateMachineOptions,\n): StateMachineProcessCache<TContext> {\n const existing = process.cache[STATE_MACHINE_PROCESS_CACHE_KEY] as StateMachineProcessCache<TContext> | undefined;\n const config = normalizeConfig(process, options, existing?.configuration);\n if (existing) {\n const established = existing.configuration;\n if (\n established.process !== process ||\n established.accountId !== config.accountId ||\n established.accountSlugId !== config.accountSlugId\n ) {\n throw new StateMachineConfigError('storageScope');\n }\n if (established.cache !== config.cache) throw new StateMachineConfigError('cache');\n if (established.implementationCompiler !== config.implementationCompiler) {\n throw new StateMachineConfigError('implementationCompiler');\n }\n if (\n Object.entries(established.executionLock).some(\n ([key, value]) => config.executionLock[key as keyof typeof config.executionLock] !== value,\n )\n ) {\n throw new StateMachineConfigError('executionLock');\n }\n return existing;\n }\n const system = constructSystem<TConfig, TContext>(process, config);\n process.cache[STATE_MACHINE_PROCESS_CACHE_KEY] = system;\n return system;\n}\n"],"mappings":"grCAiBA,MAAa,EAAkC,8BAK/C,IAAa,EAAb,cAA6C,KAAM,CACjD,OAEA,YAAY,EAA+E,CACzF,MAAM,8EAA8E,GAAQ,EAC5F,KAAK,KAAO,0BACZ,KAAK,OAAS,CAChB,CACF,EAEA,SAAS,EACP,EACA,EACA,EAC0B,CAC1B,OAAO,OAAO,OAAO,CACnB,UACA,UAAW,EAAQ,OAAO,UAC1B,cAAe,EAAQ,OAAO,cAC9B,MAAO,GAAS,OAAS,GAAa,OAAS,EAC/C,uBAAwB,GAAS,wBAA0B,GAAa,uBACxE,cAAe,EAA8B,CAC3C,iBAAkB,GAAS,eAAe,kBAAoB,GAAa,cAAc,iBACzF,gBAAiB,GAAS,eAAe,iBAAmB,GAAa,cAAc,gBACvF,aAAc,GAAS,eAAe,cAAgB,GAAa,cAAc,YACnF,CAAC,CACH,CAAC,CACH,CAMA,SAAgB,EACd,EACA,EACoC,CACpC,OAAO,EAAgB,EAAS,EAAgB,EAAS,CAAO,CAAC,CACnE,CAEA,SAAS,EACP,EACA,EACoC,CACpC,IAAM,EAAqB,IAAI,EACzB,EAAW,IAAI,EAA4B,CAAkB,EAC7D,EAAiB,IAAI,EAAiC,EAAS,CAAE,MAAO,EAAO,KAAM,CAAC,EACtF,EAAiB,IAAI,EAAiC,EAAS,CACnE,MAAO,EAAO,KAChB,CAAC,EACK,EAAY,IAAI,EAAmB,EAAgB,CAAQ,EAC3D,EAAY,IAAI,EAA0B,EAAgB,CAAS,EACnE,EAAU,IAAI,EAA8B,CAAE,uBAAwB,EAAO,sBAAuB,CAAC,EACrG,EAAU,IAAI,EAAoB,EAAW,EAAS,CAC1D,eAAgB,IAAI,EAClB,EAAO,MACP,CAAE,cAAe,EAAO,cAAe,UAAW,EAAO,UAAW,YAAa,CAAe,EAChG,EAAO,cACP,CACE,iBAAmB,GAAY,CAC7B,EAAQ,IAAI,OAAO,2EAA4E,CAAO,CACxG,EACA,kBAAoB,GAAU,CACxB,EAAM,QAAU,UAClB,EAAQ,IAAI,OAAO,2CAA4C,CAAK,EAEpE,EAAQ,IAAI,OAAO,mEAAoE,CAAK,CAEhG,CACF,CACF,CACF,CAAC,EACD,OAAO,OAAO,OAAO,CACnB,cAAe,EACf,qBACA,WACA,iBACA,iBACA,YACA,YACA,UACA,SACF,CAAC,CACH,CAOA,SAAgB,EACd,EACA,EACoC,CACpC,IAAM,EAAW,EAAQ,MAAM,GACzB,EAAS,EAAgB,EAAS,EAAS,GAAU,aAAa,EACxE,GAAI,EAAU,CACZ,IAAM,EAAc,EAAS,cAC7B,GACE,EAAY,UAAY,GACxB,EAAY,YAAc,EAAO,WACjC,EAAY,gBAAkB,EAAO,cAErC,MAAM,IAAI,EAAwB,cAAc,EAElD,GAAI,EAAY,QAAU,EAAO,MAAO,MAAM,IAAI,EAAwB,OAAO,EACjF,GAAI,EAAY,yBAA2B,EAAO,uBAChD,MAAM,IAAI,EAAwB,wBAAwB,EAE5D,GACE,OAAO,QAAQ,EAAY,aAAa,CAAC,CAAC,MACvC,CAAC,EAAK,KAAW,EAAO,cAAc,KAA8C,CACvF,EAEA,MAAM,IAAI,EAAwB,eAAe,EAEnD,OAAO,CACT,CACA,IAAM,EAAS,EAAmC,EAAS,CAAM,EAEjE,MADA,GAAQ,MAAM,GAAmC,EAC1C,CACT"}
@@ -0,0 +1,28 @@
1
+ //#region src/testing/data-in.d.mts
2
+ interface Config {
3
+ parse: (value: unknown) => unknown;
4
+ filter: (error: unknown) => Error;
5
+ base: Record<string, unknown>;
6
+ identifiers: readonly string[];
7
+ required: readonly string[];
8
+ optionalBooleans: readonly string[];
9
+ directory: URL;
10
+ }
11
+ /**
12
+ * Shared step-configuration guarantees; step-specific normalization has its own tests.
13
+ */
14
+ declare function dataInTests(config: Config): void;
15
+ //#endregion
16
+ //#region src/testing/error-filter.d.mts
17
+ type Filter = (error: unknown, options?: {
18
+ unknownMessage?: string;
19
+ unknownCode?: 'SERVER_ERROR';
20
+ preserveErrors?: readonly (new (message?: string) => Error)[];
21
+ }) => Error;
22
+ /**
23
+ * Both Flow steps must expose the same framework diagnostics and fallback behavior.
24
+ */
25
+ declare function errorFilterTests(filter: Filter): void;
26
+ //#endregion
27
+ export { dataInTests, errorFilterTests };
28
+ //# sourceMappingURL=testing.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing/data-in.mts","../src/testing/error-filter.mts"],"mappings":";UAcU;EACR,QAAQ;EACR,SAAS,mBAAmB;EAC5B,MAAM;EACN;EACA;EACA;EACA,WAAW;;;;;iBAMG,YAAY,QAAQ;;;KCR/B,UACH,gBACA;EACE;EACA;EACA,gCAAgC,qBAAqB;MAEpD;;;;iBAKW,iBAAiB,QAAQ"}
@@ -0,0 +1,39 @@
1
+ import{_ as e,a as t,f as n,g as r,h as i,l as a,m as o,o as s,p as c,s as l,t as u}from"./system-CZS-gIFs.mjs";import{t as d}from"./data-in-DT43edEv.mjs";import{createRequire as f}from"node:module";import{execFile as p}from"node:child_process";import{cp as m,mkdir as h,mkdtemp as g,readFile as _,rm as v,writeFile as y}from"node:fs/promises";import b from"node:path";import{tmpdir as x}from"node:os";import{fileURLToPath as S}from"node:url";import{promisify as C}from"node:util";import{describe as w,expect as T,expectTypeOf as E,it as D}from"vitest";const O=C(p),k=f(import.meta.url);function A(e){let{parse:t,filter:n,base:r,identifiers:i,required:a,optionalBooleans:o,directory:s}=e,c=e=>t(e);w(`AOT step configuration`,()=>{D.each([null,void 0,[],0,!1,`config`])(`rejects invalid root shapes: %j`,e=>{T(()=>t(e)).toThrow(d)}),D.each(a)(`requires %s without applying defaults`,e=>{let n={...r};delete n[e];try{throw t(n),Error(`Expected validation failure`)}catch(t){T(t).toBeInstanceOf(d),T(t.issues).toEqual(T.arrayContaining([T.objectContaining({path:`/${e}`})]))}}),D.each(i)(`normalizes and validates %s without mutating input`,e=>{let n=Object.freeze({...r,[e]:` identifier `});T(c(n)[e]).toBe(`identifier`),T(n[e]).toBe(` identifier `),T(c({...r,[e]:`a`.repeat(64)})[e]).toHaveLength(64);for(let n of[null,1,!1,` `,`undefined`,` null `,`a`.repeat(65),`😀`.repeat(33)])T(()=>t({...r,[e]:n}),`${e}: ${String(n)}`).toThrow(d)}),D(`trims timeout text without interpreting or coercing it`,()=>{T(c({...r,timeoutDuration:` 5 seconds `}).timeoutDuration).toBe(`5 seconds`),T(c({...r,timeoutDuration:`not-a-duration`}).timeoutDuration).toBe(`not-a-duration`);for(let e of[``,` `,`null`,`undefined`,100,null])T(()=>t({...r,timeoutDuration:e})).toThrow(d)}),D.each([`processError`,`processTimeout`,...o])(`does not coerce %s`,e=>{T(c({...r,[e]:!1})[e]).toBe(!1),T(()=>t({...r,[e]:`false`})).toThrow(d),T(()=>t({...r,[e]:null})).toThrow(d)}),D(`strips unknown fields without invoking their getters`,()=>{let e={...r};Object.defineProperty(e,"extra",{enumerable:!0,get(){throw Error(`Unknown getter must not run`)}}),T(c(e)).not.toHaveProperty(`extra`);for(let e of o)T(c(r)).not.toHaveProperty(e)}),D(`strips legacy test settings like other unknown configuration without reading getters`,()=>{for(let e of[void 0,null,[],!1,0,{cache:null}])T(c({...r,_testSettings:e})).not.toHaveProperty(`_testSettings`);T(c(r)).not.toHaveProperty(`_testSettings`);let e={...r};Object.defineProperty(e,"_testSettings",{enumerable:!0,get(){throw Error(`Unknown test-settings getter must not run`)}}),T(c(e)).not.toHaveProperty(`_testSettings`)}),D(`classifies parser failures as validation errors with stable issue snapshots`,()=>{let e;try{t({...r,timeoutDuration:1})}catch(t){e=t}T(e).toBeInstanceOf(d);let i=structuredClone(e.issues);T(()=>t({})).toThrow(d),T(e.issues).toEqual(i);let a=n(e);T(a).toMatchObject({code:`VALIDATION`,cause:e,data:{issues:i}}),T(a.message).toContain(`/timeoutDuration`)}),D(`ships no schema-builder or engine imports in JavaScript or declarations`,async()=>{for(let e of[`index.mjs`,`index.d.mts`]){let t=await _(new URL(`dist/${e}`,s),`utf8`);T(t).not.toMatch(/\b(?:from|import)\s*['"](?:zod|@sinclair\/typebox|ajv)(?:\/[^'"]*)?['"]/u)}let e=JSON.parse(await _(new URL(`generated/data-in.json`,s),`utf8`));T(e).toMatchObject({$schema:`https://json-schema.org/draft/2020-12/schema`,type:`object`,additionalProperties:!1}),T(e.properties).not.toHaveProperty(`_testSettings`)}),D(`preserves field descriptions and examples and validates complete configuration examples`,async()=>{let e=JSON.parse(await _(new URL(`generated/data-in.json`,s),`utf8`)),n=await _(new URL(`generated/data-in.d.mts`,s),`utf8`),r=e=>{let t=Object.values(e.properties??{});for(let e of t)T(e.description).toEqual(T.any(String)),T(e.description?.trim().length).toBeGreaterThan(0),T(e.examples?.length).toBeGreaterThan(0),T(n).toContain(e.description),r(e);let i=e.anyOf??[];for(let e of i)r(e);e.items&&r(e.items)};r(e),T(e.description?.length).toBeGreaterThan(0),T(e.examples?.length).toBeGreaterThan(0);let{isValid:i}=await import(new URL(`generated/data-in.mjs`,s).href),a=e.examples??[];for(let e of a)T(i(e)).toBe(!0),T(()=>t(e)).not.toThrow()}),D(`runs and typechecks generated validation without engines or runtime code generation`,async()=>{let e=b.join(x(),`opencode`);await h(e,{recursive:!0});let t=await g(b.join(e,`step-aot-`));try{await m(new URL(`generated/data-in.mjs`,s),b.join(t,`data-in.mjs`)),await m(new URL(`generated/data-in.d.mts`,s),b.join(t,`data-in.d.mts`)),await y(b.join(t,`runtime.mjs`),`
2
+ import assert from 'node:assert/strict';
3
+ import { isValid, validate } from './data-in.mjs';
4
+ assert.equal(isValid(${JSON.stringify(r)}), true);
5
+ assert.equal(validate({}).valid, false);
6
+ assert.equal(isValid({...${JSON.stringify(r)}, timeoutDuration: 1}), false);
7
+ `),await O(process.execPath,[`--disallow-code-generation-from-strings`,`runtime.mjs`],{cwd:t}),await y(b.join(t,`consumer.mts`),`
8
+ import type { DataInConfig } from './data-in.mjs';
9
+ import { isValid } from './data-in.mjs';
10
+ const value: DataInConfig = ${JSON.stringify(r)};
11
+ declare const raw: unknown;
12
+ if (isValid(raw)) { const timeout: string = raw.timeoutDuration; void timeout; }
13
+ void value;
14
+ `),await y(b.join(t,`tsconfig.json`),JSON.stringify({compilerOptions:{noEmit:!0,strict:!0,declaration:!0,types:[],module:`node16`,target:`es2022`},files:[`consumer.mts`]})),await O(process.execPath,[k.resolve(`typescript/bin/tsc`),`--project`,t])}finally{await v(t,{recursive:!0,force:!0})}}),D(`regenerates schemas and preserves previous artifacts when compilation fails`,async()=>{let e=new URL(`.build/`,s);await h(e,{recursive:!0});let t=await g(S(new URL(`schema-test-`,e)));try{let e=`
15
+ import assert from 'node:assert/strict';
16
+ import { pathToFileURL } from 'node:url';
17
+ import { readFile } from 'node:fs/promises';
18
+ import { generateArtifacts } from '@onereach/json-schema-aot';
19
+ const directory = pathToFileURL(${JSON.stringify(`${t}/`)});
20
+ // Generate structural configuration artifacts; normalization and SDK values stay local.
21
+ const generateStepSchema = (authored, directory) => generateArtifacts(
22
+ { DataInConfig: authored },
23
+ {
24
+ outputDirectory: new URL('generated/', directory),
25
+ temporaryDirectory: new URL('.build/', directory),
26
+ fileNames: { DataInConfig: 'data-in' },
27
+ jsonDirectory: '.',
28
+ },
29
+ );
30
+ const schema = {type: 'object', properties: {name: {type: 'string', minLength: 1}}, required: ['name'], additionalProperties: false};
31
+ await generateStepSchema(schema, directory);
32
+ const file = new URL('generated/data-in.mjs', directory);
33
+ const before = await readFile(file, 'utf8');
34
+ await assert.rejects(generateStepSchema({...schema, unsupportedKeyword: true}, directory));
35
+ assert.equal(await readFile(file, 'utf8'), before);
36
+ await generateStepSchema({...schema, properties: {name: {type: 'boolean'}}}, directory);
37
+ assert.notEqual(await readFile(file, 'utf8'), before);
38
+ `;await O(process.execPath,[`--input-type=module`,`--eval`,e],{cwd:S(s)})}finally{await v(t,{recursive:!0,force:!0})}})})}function j(f){w(`framework error filtering`,()=>{D(`restricts step error codes and fallback overrides to the shared string union`,()=>{E().toEqualTypeOf(),E().toEqualTypeOf(),E().toExtend(),E().not.toExtend()});let p=[[new c(`instance:missing`),`NOT_FOUND`,{resource:`instance:missing`}],[new l(`missing`),`NOT_FOUND`,{functionName:`missing`}],[new t(`slow`,100),`TIMEOUT`,{functionName:`slow`,timeoutMs:100}],[new o(`old`,`new`),`CONFLICT`,{expected:`old`,actual:`new`}],[new o(null,void 0),`CONFLICT`,{expected:null,actual:void 0}],[new o(void 0,`new`),`CONFLICT`,{expected:void 0,actual:`new`}],[new i(`old`,`new`),`CONFLICT`,{expected:`old`,actual:`new`}],[new n(`watch`),`UNSUPPORTED`,{capability:`watch`}],[new e(`none`),`UNSUPPORTED`,{concurrency:`none`}],[new r(`/state/value`,`unsupported value`),`VALIDATION`,{path:`/state/value`}],...[`cache`,`storageScope`].map(e=>[new a(e),`CONFIGURATION`,{option:e}])];D.each(p)(`classifies %s as %s with structured details`,(e,t,n)=>{let r=f(e,{unknownMessage:`Fallback`,unknownCode:`SERVER_ERROR`});T(r).toMatchObject({code:t,cause:e,data:n}),T(r.message).toContain(e.message),T(f(r)).toBe(r)}),D(`reports contract issues, including root paths`,()=>{let e=[{path:`/instance/id`,message:`must not be empty`},{path:``,message:`Invalid root`}],t=new u(e),n=f(t);T(n).toMatchObject({code:`VALIDATION`,cause:t,data:{issues:e}}),T(n.message).toContain(`/instance/id: must not be empty`),T(n.message).toContain(`/: Invalid root`)}),D.each([`input`,`output`,`state-before`,`state-after`,`initial-state`])(`reports %s validation with escaped pointers and unchanged issues`,e=>{let t=[{message:`Invalid root`},{path:[],message:`Invalid empty path`},{path:[`a/b`,`~key`,`0`,``],message:`Invalid value`},{path:[{key:`a/b`},0,Symbol(`key`)],message:`Invalid structured path`}],n=new s(e,t),r=f(n);T(r).toMatchObject({code:`VALIDATION`,cause:n,data:{target:e,issues:t}}),T(r.message).toContain(n.message),T(r.message).toContain(`/: Invalid root`),T(r.message).toContain(`/: Invalid empty path`),T(r.message).toContain(`/a~1b/~0key/0/: Invalid value`),T(r.message).toContain(`/a~1b/0/Symbol(key): Invalid structured path`)}),D(`handles empty validation issue arrays`,()=>{for(let e of[new u([]),new s(`input`,[])])T(f(e)).toMatchObject({code:`VALIDATION`,cause:e,message:T.stringContaining(e.message),data:{issues:[]}})}),D(`retains local configuration validation`,()=>{let e=new d([{path:`/stateId`,message:`Required`}]);T(f(e)).toMatchObject({code:`VALIDATION`,cause:e,message:T.stringContaining(e.message),data:{issues:e.issues}})}),D(`does not classify lookalike errors by name or message`,()=>{class e extends Error{name=`UnknownFunctionError`}let t=new e(`Unknown state-machine function: missing`);T(f(t)).toMatchObject({code:`UNKNOWN`,message:T.stringContaining(`Unknown error`),cause:t})}),D(`allows explicit preservation before framework classification`,()=>{let e=new c(`missing`);T(f(e,{preserveErrors:[Error]})).toBe(e)}),D(`retains unknown-error overrides and non-error payloads`,()=>{let e=Error(`Unexpected failure`);T(f(e,{unknownMessage:`Fallback`,unknownCode:`SERVER_ERROR`})).toMatchObject({code:`SERVER_ERROR`,message:T.stringContaining(`Fallback`),cause:e});for(let e of[null,void 0,42,{name:`NotFoundError`,resource:`missing`}])T(f(e)).toMatchObject({code:`UNKNOWN`,message:`Unknown error`,data:e});T(f(`Failure`)).toMatchObject({code:`UNKNOWN`,message:`Failure`})}),D(`retains legacy SDK timeout and server-response classification`,()=>{let e=Error(`Request timed out`);T(f(e)).toMatchObject({code:`TIMEOUT`,cause:e});let t=Object.assign(Error(`Request failed`),{response:{data:{error:{message:`Server failure`}}}});T(f(t)).toMatchObject({code:`SERVER_ERROR`,message:T.stringContaining(`Server failure`),cause:t})})})}export{A as dataInTests,j as errorFilterTests};
39
+ //# sourceMappingURL=testing.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.mjs","names":[],"sources":["../src/testing/data-in.mts","../src/testing/error-filter.mts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { tmpdir } from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { describe, expect, it } from 'vitest';\n\nimport { DataInValidationError } from '../configuration/data-in.mts';\n\nconst execute = promisify(execFile);\nconst require = createRequire(import.meta.url);\n\ninterface Config {\n parse: (value: unknown) => unknown;\n filter: (error: unknown) => Error;\n base: Record<string, unknown>;\n identifiers: readonly string[];\n required: readonly string[];\n optionalBooleans: readonly string[];\n directory: URL;\n}\n\n/**\n * Shared step-configuration guarantees; step-specific normalization has its own tests.\n */\nexport function dataInTests(config: Config): void {\n const { parse, filter, base, identifiers, required, optionalBooleans, directory } = config;\n const parsed = (value: unknown) => parse(value) as Record<string, unknown>;\n\n describe('AOT step configuration', () => {\n it.each([null, undefined, [], 0, false, 'config'])('rejects invalid root shapes: %j', (value) => {\n expect(() => parse(value)).toThrow(DataInValidationError);\n });\n\n it.each(required)('requires %s without applying defaults', (field) => {\n const value = { ...base };\n delete value[field];\n try {\n parse(value);\n throw new Error('Expected validation failure');\n } catch (error) {\n expect(error).toBeInstanceOf(DataInValidationError);\n expect((error as DataInValidationError).issues).toEqual(\n expect.arrayContaining([expect.objectContaining({ path: `/${field}` })]),\n );\n }\n });\n\n it.each(identifiers)('normalizes and validates %s without mutating input', (field) => {\n const value = Object.freeze({ ...base, [field]: ' identifier ' });\n expect(parsed(value)[field]).toBe('identifier');\n expect(value[field]).toBe(' identifier ');\n expect(parsed({ ...base, [field]: 'a'.repeat(64) })[field]).toHaveLength(64);\n for (const invalid of [null, 1, false, ' ', 'undefined', ' null ', 'a'.repeat(65), '😀'.repeat(33)]) {\n expect(() => parse({ ...base, [field]: invalid }), `${field}: ${String(invalid)}`).toThrow(\n DataInValidationError,\n );\n }\n });\n\n it('trims timeout text without interpreting or coercing it', () => {\n expect(parsed({ ...base, timeoutDuration: ' 5 seconds ' }).timeoutDuration).toBe('5 seconds');\n expect(parsed({ ...base, timeoutDuration: 'not-a-duration' }).timeoutDuration).toBe('not-a-duration');\n for (const timeoutDuration of ['', ' ', 'null', 'undefined', 100, null])\n expect(() => parse({ ...base, timeoutDuration })).toThrow(DataInValidationError);\n });\n\n it.each(['processError', 'processTimeout', ...optionalBooleans])('does not coerce %s', (field) => {\n expect(parsed({ ...base, [field]: false })[field]).toBe(false);\n expect(() => parse({ ...base, [field]: 'false' })).toThrow(DataInValidationError);\n expect(() => parse({ ...base, [field]: null })).toThrow(DataInValidationError);\n });\n\n it('strips unknown fields without invoking their getters', () => {\n const value = { ...base };\n Object.defineProperty(value, 'extra', {\n enumerable: true,\n get() {\n throw new Error('Unknown getter must not run');\n },\n });\n expect(parsed(value)).not.toHaveProperty('extra');\n for (const field of optionalBooleans) expect(parsed(base)).not.toHaveProperty(field);\n });\n\n it('strips legacy test settings like other unknown configuration without reading getters', () => {\n for (const settings of [undefined, null, [], false, 0, { cache: null }]) {\n expect(parsed({ ...base, _testSettings: settings })).not.toHaveProperty('_testSettings');\n }\n expect(parsed(base)).not.toHaveProperty('_testSettings');\n const value = { ...base };\n Object.defineProperty(value, '_testSettings', {\n enumerable: true,\n get() {\n throw new Error('Unknown test-settings getter must not run');\n },\n });\n expect(parsed(value)).not.toHaveProperty('_testSettings');\n });\n\n it('classifies parser failures as validation errors with stable issue snapshots', () => {\n let first: unknown;\n try {\n parse({ ...base, timeoutDuration: 1 });\n } catch (error) {\n first = error;\n }\n expect(first).toBeInstanceOf(DataInValidationError);\n const issues = structuredClone((first as DataInValidationError).issues);\n expect(() => parse({})).toThrow(DataInValidationError);\n expect((first as DataInValidationError).issues).toEqual(issues);\n const filtered = filter(first);\n expect(filtered).toMatchObject({ code: 'VALIDATION', cause: first, data: { issues } });\n expect(filtered.message).toContain('/timeoutDuration');\n });\n\n it('ships no schema-builder or engine imports in JavaScript or declarations', async () => {\n for (const file of ['index.mjs', 'index.d.mts']) {\n const content = await readFile(new URL(`dist/${file}`, directory), 'utf8');\n expect(content).not.toMatch(/\\b(?:from|import)\\s*['\"](?:zod|@sinclair\\/typebox|ajv)(?:\\/[^'\"]*)?['\"]/u);\n }\n const schema = JSON.parse(await readFile(new URL('generated/data-in.json', directory), 'utf8'));\n expect(schema).toMatchObject({\n $schema: 'https://json-schema.org/draft/2020-12/schema',\n type: 'object',\n additionalProperties: false,\n });\n expect(schema.properties).not.toHaveProperty('_testSettings');\n });\n\n it('preserves field descriptions and examples and validates complete configuration examples', async () => {\n interface Schema {\n description?: string;\n examples?: unknown[];\n properties?: Record<string, Schema>;\n anyOf?: Schema[];\n items?: Schema;\n }\n const schema = JSON.parse(await readFile(new URL('generated/data-in.json', directory), 'utf8')) as Schema;\n const declarations = await readFile(new URL('generated/data-in.d.mts', directory), 'utf8');\n const checkFields = (node: Schema): void => {\n const properties = Object.values(node.properties ?? {});\n for (const property of properties) {\n expect(property.description).toEqual(expect.any(String));\n expect(property.description?.trim().length).toBeGreaterThan(0);\n expect(property.examples?.length).toBeGreaterThan(0);\n expect(declarations).toContain(property.description);\n checkFields(property);\n }\n const branches = node.anyOf ?? [];\n for (const branch of branches) checkFields(branch);\n if (node.items) checkFields(node.items);\n };\n checkFields(schema);\n expect(schema.description?.length).toBeGreaterThan(0);\n expect(schema.examples?.length).toBeGreaterThan(0);\n const { isValid } = (await import(new URL('generated/data-in.mjs', directory).href)) as {\n isValid: (value: unknown) => boolean;\n };\n const examples = schema.examples ?? [];\n for (const example of examples) {\n expect(isValid(example)).toBe(true);\n expect(() => parse(example)).not.toThrow();\n }\n });\n\n it('runs and typechecks generated validation without engines or runtime code generation', async () => {\n const parent = path.join(tmpdir(), 'opencode');\n await mkdir(parent, { recursive: true });\n const temporary = await mkdtemp(path.join(parent, 'step-aot-'));\n try {\n await cp(new URL('generated/data-in.mjs', directory), path.join(temporary, 'data-in.mjs'));\n await cp(new URL('generated/data-in.d.mts', directory), path.join(temporary, 'data-in.d.mts'));\n await writeFile(\n path.join(temporary, 'runtime.mjs'),\n `\nimport assert from 'node:assert/strict';\nimport { isValid, validate } from './data-in.mjs';\nassert.equal(isValid(${JSON.stringify(base)}), true);\nassert.equal(validate({}).valid, false);\nassert.equal(isValid({...${JSON.stringify(base)}, timeoutDuration: 1}), false);\n`,\n );\n await execute(process.execPath, ['--disallow-code-generation-from-strings', 'runtime.mjs'], { cwd: temporary });\n await writeFile(\n path.join(temporary, 'consumer.mts'),\n `\nimport type { DataInConfig } from './data-in.mjs';\nimport { isValid } from './data-in.mjs';\nconst value: DataInConfig = ${JSON.stringify(base)};\ndeclare const raw: unknown;\nif (isValid(raw)) { const timeout: string = raw.timeoutDuration; void timeout; }\nvoid value;\n`,\n );\n await writeFile(\n path.join(temporary, 'tsconfig.json'),\n JSON.stringify({\n compilerOptions: {\n noEmit: true,\n strict: true,\n declaration: true,\n types: [],\n module: 'node16',\n target: 'es2022',\n },\n files: ['consumer.mts'],\n }),\n );\n await execute(process.execPath, [require.resolve('typescript/bin/tsc'), '--project', temporary]);\n } finally {\n await rm(temporary, { recursive: true, force: true });\n }\n });\n\n it('regenerates schemas and preserves previous artifacts when compilation fails', async () => {\n const temporary = new URL('.build/', directory);\n await mkdir(temporary, { recursive: true });\n const work = await mkdtemp(fileURLToPath(new URL('schema-test-', temporary)));\n try {\n const script = `\nimport assert from 'node:assert/strict';\nimport { pathToFileURL } from 'node:url';\nimport { readFile } from 'node:fs/promises';\nimport { generateArtifacts } from '@onereach/json-schema-aot';\nconst directory = pathToFileURL(${JSON.stringify(`${work}/`)});\n// Generate structural configuration artifacts; normalization and SDK values stay local.\nconst generateStepSchema = (authored, directory) => generateArtifacts(\n { DataInConfig: authored },\n {\n outputDirectory: new URL('generated/', directory),\n temporaryDirectory: new URL('.build/', directory),\n fileNames: { DataInConfig: 'data-in' },\n jsonDirectory: '.',\n },\n);\nconst schema = {type: 'object', properties: {name: {type: 'string', minLength: 1}}, required: ['name'], additionalProperties: false};\nawait generateStepSchema(schema, directory);\nconst file = new URL('generated/data-in.mjs', directory);\nconst before = await readFile(file, 'utf8');\nawait assert.rejects(generateStepSchema({...schema, unsupportedKeyword: true}, directory));\nassert.equal(await readFile(file, 'utf8'), before);\nawait generateStepSchema({...schema, properties: {name: {type: 'boolean'}}}, directory);\nassert.notEqual(await readFile(file, 'utf8'), before);\n`;\n await execute(process.execPath, ['--input-type=module', '--eval', script], {\n cwd: fileURLToPath(directory),\n });\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n });\n });\n}\n","import {\n ContractValidationError,\n DriverCapabilityError,\n FunctionTimeoutError,\n NotFoundError,\n RevisionConflictError,\n SchemaValidationError,\n StateMachineConfigError,\n TemplateRevisionMismatchError,\n TemplateSnapshotError,\n UnknownFunctionError,\n UnsafeConcurrencyError,\n} from '../system/index.ts';\nimport { describe, expect, expectTypeOf, it } from 'vitest';\n\nimport { DataInValidationError } from '../configuration/data-in.mts';\nimport type { StepErrorCode } from '../errors/error-code.mts';\nimport type { ErrorFilterOptions, StepErrorDetails } from '../errors/error-filter.mts';\n\ntype Filter = (\n error: unknown,\n options?: {\n unknownMessage?: string;\n unknownCode?: 'SERVER_ERROR';\n preserveErrors?: readonly (new (message?: string) => Error)[];\n },\n) => Error;\n\n/**\n * Both Flow steps must expose the same framework diagnostics and fallback behavior.\n */\nexport function errorFilterTests(filter: Filter): void {\n describe('framework error filtering', () => {\n it('restricts step error codes and fallback overrides to the shared string union', () => {\n expectTypeOf<StepErrorDetails['code']>().toEqualTypeOf<StepErrorCode>();\n expectTypeOf<NonNullable<ErrorFilterOptions<[]>['unknownCode']>>().toEqualTypeOf<StepErrorCode>();\n expectTypeOf<'VALIDATION'>().toExtend<StepErrorCode>();\n expectTypeOf<'VALIDATON'>().not.toExtend<StepErrorCode>();\n });\n\n const cases = [\n [new NotFoundError('instance:missing'), 'NOT_FOUND', { resource: 'instance:missing' }],\n [new UnknownFunctionError('missing'), 'NOT_FOUND', { functionName: 'missing' }],\n [new FunctionTimeoutError('slow', 100), 'TIMEOUT', { functionName: 'slow', timeoutMs: 100 }],\n [new RevisionConflictError('old', 'new'), 'CONFLICT', { expected: 'old', actual: 'new' }],\n [new RevisionConflictError(null, undefined), 'CONFLICT', { expected: null, actual: undefined }],\n [new RevisionConflictError(undefined, 'new'), 'CONFLICT', { expected: undefined, actual: 'new' }],\n [new TemplateRevisionMismatchError('old', 'new'), 'CONFLICT', { expected: 'old', actual: 'new' }],\n [new DriverCapabilityError('watch'), 'UNSUPPORTED', { capability: 'watch' }],\n [new UnsafeConcurrencyError('none'), 'UNSUPPORTED', { concurrency: 'none' }],\n [new TemplateSnapshotError('/state/value', 'unsupported value'), 'VALIDATION', { path: '/state/value' }],\n ...(['cache', 'storageScope'] as const).map(\n (option) => [new StateMachineConfigError(option), 'CONFIGURATION', { option }] as const,\n ),\n ] as const;\n\n it.each(cases)('classifies %s as %s with structured details', (cause, code, data) => {\n const result = filter(cause, { unknownMessage: 'Fallback', unknownCode: 'SERVER_ERROR' });\n expect(result).toMatchObject({ code, cause, data });\n expect(result.message).toContain(cause.message);\n expect(filter(result)).toBe(result);\n });\n\n it('reports contract issues, including root paths', () => {\n const issues = [\n { path: '/instance/id', message: 'must not be empty' },\n { path: '', message: 'Invalid root' },\n ];\n const cause = new ContractValidationError(issues);\n const result = filter(cause);\n expect(result).toMatchObject({ code: 'VALIDATION', cause, data: { issues } });\n expect(result.message).toContain('/instance/id: must not be empty');\n expect(result.message).toContain('/: Invalid root');\n });\n\n it.each(['input', 'output', 'state-before', 'state-after', 'initial-state'] as const)(\n 'reports %s validation with escaped pointers and unchanged issues',\n (target) => {\n const issues = [\n { message: 'Invalid root' },\n { path: [], message: 'Invalid empty path' },\n { path: ['a/b', '~key', '0', ''], message: 'Invalid value' },\n { path: [{ key: 'a/b' }, 0, Symbol('key')], message: 'Invalid structured path' },\n ];\n const cause = new SchemaValidationError(target, issues);\n const result = filter(cause);\n expect(result).toMatchObject({ code: 'VALIDATION', cause, data: { target, issues } });\n expect(result.message).toContain(cause.message);\n expect(result.message).toContain('/: Invalid root');\n expect(result.message).toContain('/: Invalid empty path');\n expect(result.message).toContain('/a~1b/~0key/0/: Invalid value');\n expect(result.message).toContain('/a~1b/0/Symbol(key): Invalid structured path');\n },\n );\n\n it('handles empty validation issue arrays', () => {\n for (const cause of [new ContractValidationError([]), new SchemaValidationError('input', [])]) {\n expect(filter(cause)).toMatchObject({\n code: 'VALIDATION',\n cause,\n message: expect.stringContaining(cause.message),\n data: { issues: [] },\n });\n }\n });\n\n it('retains local configuration validation', () => {\n const cause = new DataInValidationError([{ path: '/stateId', message: 'Required' }]);\n expect(filter(cause)).toMatchObject({\n code: 'VALIDATION',\n cause,\n message: expect.stringContaining(cause.message),\n data: { issues: cause.issues },\n });\n });\n\n it('does not classify lookalike errors by name or message', () => {\n class LookalikeError extends Error {\n override name = 'UnknownFunctionError';\n }\n const cause = new LookalikeError('Unknown state-machine function: missing');\n expect(filter(cause)).toMatchObject({\n code: 'UNKNOWN',\n message: expect.stringContaining('Unknown error'),\n cause,\n });\n });\n\n it('allows explicit preservation before framework classification', () => {\n const cause = new NotFoundError('missing');\n expect(filter(cause, { preserveErrors: [Error] })).toBe(cause);\n });\n\n it('retains unknown-error overrides and non-error payloads', () => {\n const cause = new Error('Unexpected failure');\n expect(filter(cause, { unknownMessage: 'Fallback', unknownCode: 'SERVER_ERROR' })).toMatchObject({\n code: 'SERVER_ERROR',\n message: expect.stringContaining('Fallback'),\n cause,\n });\n for (const data of [null, undefined, 42, { name: 'NotFoundError', resource: 'missing' }]) {\n expect(filter(data)).toMatchObject({ code: 'UNKNOWN', message: 'Unknown error', data });\n }\n expect(filter('Failure')).toMatchObject({ code: 'UNKNOWN', message: 'Failure' });\n });\n\n it('retains legacy SDK timeout and server-response classification', () => {\n const timeout = new Error('Request timed out');\n expect(filter(timeout)).toMatchObject({ code: 'TIMEOUT', cause: timeout });\n const cause = Object.assign(new Error('Request failed'), {\n response: { data: { error: { message: 'Server failure' } } },\n });\n expect(filter(cause)).toMatchObject({\n code: 'SERVER_ERROR',\n message: expect.stringContaining('Server failure'),\n cause,\n });\n });\n });\n}\n"],"mappings":"yiBAWA,MAAM,EAAU,EAAU,CAAQ,EAC5B,EAAU,EAAc,YAAY,GAAG,EAe7C,SAAgB,EAAY,EAAsB,CAChD,GAAM,CAAE,QAAO,SAAQ,OAAM,cAAa,WAAU,mBAAkB,aAAc,EAC9E,EAAU,GAAmB,EAAM,CAAK,EAE9C,EAAS,6BAAgC,CACvC,EAAG,KAAK,CAAC,KAAM,IAAA,GAAW,CAAC,EAAG,EAAG,GAAO,QAAQ,CAAC,CAAC,CAAC,kCAAoC,GAAU,CAC/F,MAAa,EAAM,CAAK,CAAC,CAAC,CAAC,QAAQ,CAAqB,CAC1D,CAAC,EAED,EAAG,KAAK,CAAQ,CAAC,CAAC,wCAA0C,GAAU,CACpE,IAAM,EAAQ,CAAE,GAAG,CAAK,EACxB,OAAO,EAAM,GACb,GAAI,CAEF,MADA,EAAM,CAAK,EACD,MAAM,6BAA6B,CAC/C,OAAS,EAAO,CACd,EAAO,CAAK,CAAC,CAAC,eAAe,CAAqB,EAClD,EAAQ,EAAgC,MAAM,CAAC,CAAC,QAC9C,EAAO,gBAAgB,CAAC,EAAO,iBAAiB,CAAE,KAAM,IAAI,GAAQ,CAAC,CAAC,CAAC,CACzE,CACF,CACF,CAAC,EAED,EAAG,KAAK,CAAW,CAAC,CAAC,qDAAuD,GAAU,CACpF,IAAM,EAAQ,OAAO,OAAO,CAAE,GAAG,GAAO,GAAQ,cAAe,CAAC,EAChE,EAAO,EAAO,CAAK,CAAC,CAAC,EAAM,CAAC,CAAC,KAAK,YAAY,EAC9C,EAAO,EAAM,EAAM,CAAC,CAAC,KAAK,cAAc,EACxC,EAAO,EAAO,CAAE,GAAG,GAAO,GAAQ,IAAI,OAAO,EAAE,CAAE,CAAC,CAAC,CAAC,EAAM,CAAC,CAAC,aAAa,EAAE,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"name": "@onereach/step-state-machine-shared",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-framework.13",
4
+ "description": "Shared OneReach state-machine step composition, configuration, and errors",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "keywords": [
8
+ "onereach",
9
+ "toolkit",
10
+ "state-machine"
11
+ ],
12
+ "author": "OneReach Development Team",
13
+ "license": "Apache-2.0",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "!dist/metafile*.json"
20
+ ],
21
+ "devDependencies": {
22
+ "@arethetypeswrong/core": "^0.18.5",
23
+ "@onereach/flow-sdk": "v9.0.0-monosplit.5",
24
+ "@onereach/flow-sdk-mocks": "v9.0.0-monosplit.5",
25
+ "@onereach/state-machine-runtime-node-worker": "1.0.0-framework.2",
26
+ "@types/node": "^24.13.3",
27
+ "publint": "^0.3.24",
28
+ "tsdown": "^0.22.14",
29
+ "typescript": "^6.0.3",
30
+ "vitest": "^4.1.11"
31
+ },
32
+ "dependencies": {
33
+ "@onereach/state-machine-contracts": "1.0.0-framework.12",
34
+ "@onereach/state-machine-coordination": "1.0.0-framework.2",
35
+ "@onereach/state-machine-coordination-onereach": "1.0.0-framework.2",
36
+ "@onereach/state-machine-driver-or-flow-mf": "1.0.0-framework.12",
37
+ "@onereach/state-machine-json-schema-ajv": "1.0.0-framework.12",
38
+ "@onereach/state-machine-runtime": "1.0.0-framework.13",
39
+ "@onereach/state-machine-service": "1.0.0-framework.13",
40
+ "@onereach/state-machine-store": "1.0.0-framework.12",
41
+ "@onereach/state-machine-validation": "1.0.0-framework.2"
42
+ },
43
+ "peerDependencies": {
44
+ "vitest": "^4.1.11"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "vitest": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "exports": {
52
+ ".": "./dist/index.mjs",
53
+ "./configuration": "./dist/configuration.mjs",
54
+ "./errors": "./dist/errors.mjs",
55
+ "./notifications": "./dist/notifications.mjs",
56
+ "./testing": "./dist/testing.mjs",
57
+ "./package.json": "./package.json"
58
+ },
59
+ "scripts": {
60
+ "build": "tsdown --config tsdown.config.mts",
61
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile .cache/typecheck/source.tsbuildinfo && tsc --noEmit -p test/tsconfig.json --incremental --tsBuildInfoFile .cache/typecheck/test.tsbuildinfo",
62
+ "test": "pnpm run unit",
63
+ "unit": "vitest run",
64
+ "unit:coverage": "vitest run --coverage",
65
+ "preversion": "pnpm build"
66
+ }
6
67
  }