@onereach/state-machine-validation 0.0.0-stage → 1.0.0-framework.4

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,265 @@
1
- # Temporary Holding Version
1
+ # @onereach/state-machine-validation
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
+ Engine-independent preparation of template-supplied JSON Schemas and validation
4
+ of state, function input, and function output. This package depends on contracts'
5
+ data types, not on AJV or another runtime schema engine. The
6
+ runtime compiler protocol belongs here, not in contracts.
7
+
8
+ ```ts
9
+ import { CachedStateTemplatePreparer } from '@onereach/state-machine-validation';
10
+ import { AjvJsonSchemaValidatorCompiler } from '@onereach/state-machine-json-schema-ajv';
11
+ import { StateTemplateStore } from '@onereach/state-machine-store';
12
+
13
+ const preparer = new CachedStateTemplatePreparer(new AjvJsonSchemaValidatorCompiler(), { maxRevisions: 256 });
14
+ const templates = new StateTemplateStore(driver, preparer);
15
+ ```
16
+
17
+ `StateTemplatePreparer.prepare(template)` prepares state/input/output validators and checks
18
+ `initialState` before returning a complete validator collection. The injected
19
+ `JsonSchemaValidatorCompiler` owns dialect, keyword, and reference validation.
20
+ The store still prepares before persistence and binds successful preparation to
21
+ the revision returned by storage without recompiling.
22
+ `SchemaTarget` (`state`, `input`, or `output`) belongs to the validation type layer;
23
+ preparation and its telemetry adapter share it without deriving domain types from
24
+ instrumentation.
25
+
26
+ `StateTemplatePreparer` is uncached: each call compiles all schemas and checks
27
+ initial state again. Its `bind(identity, validators)` deliberately does nothing:
28
+ it accepts post-persistence notifications without inspecting or retaining them.
29
+ It can be used independently or injected into a store for uncached preparation.
30
+ Both preparers structurally satisfy the store-owned `StateTemplatePreparation`
31
+ capability; validation has no dependency on the store. Composition chooses the
32
+ compiler and caching policy, never the store.
33
+ `CachedStateTemplatePreparer` wraps the same preparation operation with:
34
+
35
+ - Schema and parsed-template identities use weak maps.
36
+ - Immutable revision identities use an LRU map with `get`, `bind`, `invalidate`,
37
+ and `clearRevisionCache` operations. Capacity defaults to 256 revisions;
38
+ `maxRevisions: 0` disables strong revision retention. Negative, fractional,
39
+ infinite, and unsafe capacities are rejected.
40
+ - Only successful schema compilations and complete preparations are cached.
41
+ - Schemas, templates, and initial state must remain immutable after preparation;
42
+ callers must not reuse an identity for different content.
43
+ - Clearing or evicting revisions does not clear weak identity caches. A retained
44
+ template object can still reuse its result; use a new object graph for new data.
45
+
46
+ Neither preparer freezes or clones caller-owned templates. Preparation assumes
47
+ canonical contract validation has already completed. Runtime data validation
48
+ remains non-transforming. Treat the complete schema/template graph as immutable
49
+ once supplied to the cached preparer; mutation is unsupported, not detected or
50
+ automatically recompiled.
51
+
52
+ Preparation accepts `ReadonlyStateMachineTemplate` views as well as mutable
53
+ authored templates. Store callers supply owned immutable snapshots; direct
54
+ preparer callers remain responsible for immutable input graphs. Preparation does
55
+ not apply the store's additional JSON-data snapshot restrictions by itself.
56
+
57
+ Prepared collections and per-function entries are frozen. The function lookup
58
+ implements `ReadonlyMap` without exposing a mutable `Map`, including through
59
+ iteration and `forEach`. Adapter-provided validator objects remain adapter-owned.
60
+
61
+ ## Revision identity and compiler scope
62
+
63
+ `prepare(template, identity)`, `get(identity)`, `bind(identity, validators)`, and
64
+ `invalidate(identity)` accept `StateTemplateRevisionIdentity`:
65
+
66
+ ```ts
67
+ const identity = {
68
+ namespace: 'tenant-a:templates',
69
+ templateId: template.id,
70
+ templateVersion: template.version,
71
+ revision: persistedRevision,
72
+ };
73
+ const validators = preparer.prepare(template, identity);
74
+ ```
75
+
76
+ Namespace must identify the tenant and storage location; revision must identify
77
+ immutable content within that namespace and template ID/version. Omitted version
78
+ is distinct from a literal version such as `"latest"`. The store supplies its own
79
+ isolated namespace per driver identity, so sharing a preparer cannot mix drivers.
80
+ Stores sharing the same driver object can reuse prepared revisions.
81
+ Preparation rejects identities whose template ID/version do not match the input.
82
+
83
+ The revision LRU is retained independently of the store's loaded-snapshot LRU:
84
+ new snapshots created after store eviction/reset and snapshots loaded by another
85
+ store have different object identities. Revision reuse avoids recompiling their
86
+ schemas without retaining the loaded wrapper or executable as a cache artifact.
87
+ Injected engine validators may themselves retain schema graphs; this is not a
88
+ global memory bound. Configure `maxRevisions` separately from the store's
89
+ `maxCachedTemplates`. Zero store capacity alone does not disable validator reuse.
90
+
91
+ Each preparer is scoped to one fixed compiler configuration. Do not mutate that
92
+ configuration after use; create a new preparer instead. `bind` accepts only
93
+ complete results produced by that cached preparer, preventing cross-compiler reuse.
94
+ Bind only after successful persistence. Revision eviction releases this cache's
95
+ strong reference, not references held by adapters, stores, runtimes, or callers.
96
+
97
+ `assertSchema` throws `SchemaValidationError` with the target, message, and
98
+ `readonly issues: readonly SchemaValidationIssue[]`. The constructor requires an
99
+ array (use `[]` when empty) and copies the array, issue records, and any path
100
+ arrays/segment objects. Omitted paths remain omitted.
101
+ Engine-specific nested parameters remain the adapter's per-call snapshots.
102
+ Contract errors and pure semantic checks remain in contracts.
103
+
104
+ ## Compiled validation results
105
+
106
+ `JsonSchemaValidatorCompiler.compile<T>(schema)` returns a
107
+ `SynchronousDataValidator<T, SchemaValidationIssue>`, which implements Standard Schema v1 directly.
108
+ Its synchronous `validator['~standard'].validate(value)` method returns:
109
+
110
+ - `{ value: T }`, where `value` is the original input.
111
+ - `{ issues: readonly SchemaValidationIssue[] }`, with issues
112
+ owned by that validation call.
113
+
114
+ Validation never clones successful values, supplies defaults, coerces input, or
115
+ strips properties. Earlier results remain independent of subsequent validations;
116
+ there is no mutable "last issues" property. Adapters must normalize and snapshot
117
+ their engine's errors before returning a failure.
118
+
119
+ The generic `T` is a caller-supplied type assertion, not TypeScript inference from
120
+ an arbitrary runtime JSON Schema. These validators do not implement creation
121
+ transformations or the full `Contract` interface.
122
+
123
+ ## Standard Schema as the engine protocol
124
+
125
+ Pass a compiled runtime validator directly to a Standard Schema consumer.
126
+ There is no adapter or separate native validation method:
127
+
128
+ ```ts
129
+ import { AjvJsonSchemaValidatorCompiler } from '@onereach/state-machine-json-schema-ajv';
130
+
131
+ const compiler = new AjvJsonSchemaValidatorCompiler();
132
+ const compiled = compiler.compile<{ counter: number }>({
133
+ type: 'object',
134
+ properties: { counter: { type: 'integer' } },
135
+ required: ['counter'],
136
+ });
137
+ const result = compiled['~standard'].validate({ counter: 1 });
138
+ if (result.issues) {
139
+ console.error(result.issues);
140
+ } else {
141
+ console.log(result.value.counter);
142
+ }
143
+ ```
144
+
145
+ `SynchronousDataValidator<T, Issue>` narrows Standard Schema's allowed result to
146
+ synchronous, non-transforming validation. `Issue` defaults to
147
+ `StandardSchemaV1.Issue`; runtime execution requires no JSON Schema compilation
148
+ or engine fields. Engines
149
+ identify themselves through the standard vendor metadata (AJV uses
150
+ `@onereach/state-machine-json-schema-ajv`). Input and output types are the same
151
+ caller-asserted `T`, not inferred from arbitrary runtime JSON Schema.
152
+ Unexpected engine exceptions propagate rather than becoming data issues.
153
+ Standard Schema permits synchronous results; generic consumers should still
154
+ support promises from other implementations.
155
+
156
+ JSON Schema engines expose required messages and decoded JSON Pointer segments. Root paths become
157
+ `[]`; escaped property names are decoded once. Numeric segments remain strings
158
+ because JSON Pointers cannot distinguish array indices from numeric object keys.
159
+ Missing messages fall back to the engine keyword, then `Invalid value`.
160
+ Engine paths are preserved semantically: required-property paths are not rewritten
161
+ using engine-specific parameters. `keyword`, `schemaPath`, and `params` remain
162
+ available as optional issue extensions on that same result. Generic Standard
163
+ Schema consumers may discard these extensions. Other data validators may use any
164
+ Standard Schema path form, including omitted paths, numeric/symbol keys, and
165
+ `{ key }` segments. `assertSchema`, template preparation,
166
+ and runtime execution all consume this one Standard Schema operation.
167
+
168
+ This protocol does not add parsing defaults, transformations, JSON Schema
169
+ conversion, or the contracts package's `Contract` interface. Compilation, dialect
170
+ validation, and reference resolution remain the injected engine's responsibility.
171
+
172
+ ## Compilation versus execution
173
+
174
+ ### Preparation tracing
175
+
176
+ Cache lookups also increment the API-only
177
+ `state_machine.preparation.cache.requests` counter with only `cache` (`revision`,
178
+ `template`, `schema`) and `result` (`hit`, `miss`). Only reached lookups count:
179
+ a revision hit skips template/schema lookups, and a template hit skips schemas.
180
+ Explicit revision `get` counts; bind/invalidate/clear and uncached preparation do
181
+ not. Failed compilation/preparation still counts its reached misses. These are
182
+ lookup counts, not cache occupancy or proof of fresh engine compilation.
183
+ Metrics work independently of spans; hosts own meter providers/readers/exporters.
184
+ Reporting failures cannot alter caching or replay compilation.
185
+
186
+ `template.prepare` measures synchronous preparation and initial-state validation.
187
+ `schema.compile` measures calls to the injected compiler with only a bounded
188
+ `state_machine.preparation.schema_target` (`state`, `input`, or `output`).
189
+ The uncached preparer emits spans on every call. The cached preparer emits them
190
+ only on the corresponding template/revision or schema-identity miss. A new
191
+ template reusing compiled schemas emits no schema spans; a template/revision hit
192
+ emits neither. Successful schema compilations remain cached after a later
193
+ preparation failure, but partial template collections are never published.
194
+
195
+ These are compiler-call spans, not evidence of fresh engine code generation;
196
+ engine-internal caches remain opaque. Direct compiler calls are not instrumented.
197
+ The package uses only the OpenTelemetry API; hosts own providers and context
198
+ management, including parent correlation and nested schema spans. Preparation
199
+ remains synchronous and runs once even if tracing fails, preserving return/error
200
+ identity. No schemas, state, names, revisions, or raw errors are recorded.
201
+ See the [telemetry reference](../../docs/architecture/telemetry.md).
202
+
203
+ ### Execution-facing validators
204
+
205
+ `JsonSchemaValidatorCompiler` remains the preparation boundary for persisted
206
+ JSON Schemas. It returns data validators with optional engine diagnostics.
207
+ The optional `@onereach/state-machine-json-schema-ajv` integration implements that
208
+ compiler using AJV. The composition root selects it; this package has no AJV
209
+ dependency or engine-specific setup logic.
210
+ `FunctionValidators` and `StateTemplateValidators` are execution-facing
211
+ collections of `SynchronousDataValidator` values, with no compilation requirement.
212
+ The JSON Schema preparers produce these same collections, but callers may also
213
+ provide independent data validators directly to the runtime.
214
+
215
+ Keep `assertSchema` as the common targeted-error boundary. Do not add store,
216
+ service, or runtime wrappers to reinterpret validation results. Validators supplied
217
+ directly must preserve successful input identity and never coerce, default, strip,
218
+ or otherwise transform data. Standard Schema compatibility alone does not enforce
219
+ these semantic guarantees; potentially asynchronous or transforming validators
220
+ are not automatically suitable for runtime execution.
221
+
222
+ ## Import migration
223
+
224
+ These exports moved out of the former `@onereach/state-machine-core` package
225
+ (now `@onereach/state-machine-contracts`) to this package:
226
+
227
+ - Template preparation (now `StateTemplatePreparer` / `CachedStateTemplatePreparer`)
228
+ - Execution collections (now `FunctionValidators` and `StateTemplateValidators`)
229
+ - `assertSchema`, `SchemaValidationError`, and `SchemaValidationTarget`
230
+ - `JsonSchemaValidatorCompiler`
231
+ - `SchemaValidationIssue`
232
+
233
+ Replace `SchemaValidator<T>` / `CompiledJsonSchemaValidator<T>` with
234
+ `SynchronousDataValidator<T>`. Replace `CompiledFunctionValidators` and
235
+ `CompiledStateTemplateValidators` with `FunctionValidators` and
236
+ `StateTemplateValidators`. No compatibility aliases are exported.
237
+ Call `validator['~standard'].validate(value)`, then inspect `result.issues`:
238
+ if present, validation failed (including an empty issue array); otherwise read
239
+ `result.value`. Remove `toStandardSchema` wrappers. `StandardSchemaAdapter` and
240
+ `SchemaValidationResult` are no longer exported, and there is no duplicate
241
+ `validator.validate()` method or compatibility alias.
242
+
243
+ Runtime `SchemaValidationIssue` values require only `message`, support all
244
+ optional Standard Schema `path` forms, and allow optional `keyword`, `schemaPath`,
245
+ and `params` extensions.
246
+ This applies to both validation results and `SchemaValidationError.issues`,
247
+ including forwarded step error payloads. Step error display messages still use
248
+ escaped JSON Pointers. Runtime issues are distinct from contracts' engine-independent
249
+ `ContractIssue` values (`path` and required `message` only).
250
+ Contract errors and runtime errors are converted to their own public diagnostics
251
+ at their respective boundaries.
252
+
253
+ There is no contracts re-export of the runtime validation protocol, avoiding a
254
+ dependency back from contracts to preparation. The step-service public
255
+ `SchemaValidationError` re-export remains available.
256
+
257
+ Replace `new StateTemplateValidatorCompiler(engine).compile(template, key)` with
258
+ `new CachedStateTemplatePreparer(engine).prepare(template, identity)`, or use
259
+ `StateTemplatePreparer` when caching is unnecessary. There is no old-name alias.
260
+ Replace `SchemaValidationError.errors` with `.issues`; nullable diagnostics are
261
+ no longer accepted. Step validation error data now also uses `issues`.
262
+
263
+ Build dependencies first with
264
+ `pnpm exec turbo run build --filter=@onereach/state-machine-validation`, then run
265
+ `pnpm --filter @onereach/state-machine-validation exec vitest run`.
@@ -0,0 +1,136 @@
1
+ import { JsonSchema, ReadonlyStateMachineTemplate } from "@onereach/state-machine-contracts";
2
+ import { StandardSchemaV1 } from "@standard-schema/spec";
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Preparation role of a template-supplied schema, independent of instrumentation.
6
+ */
7
+ type SchemaTarget = 'state' | 'input' | 'output';
8
+ /**
9
+ * Standard Schema diagnostic with optional runtime-engine details.
10
+ * Consumers require only standard messages and optional paths. JSON Schema
11
+ * engines decode pointers into string segments; other implementations may use
12
+ * any Standard Schema path representation.
13
+ */
14
+ interface SchemaValidationIssue extends StandardSchemaV1.Issue {
15
+ keyword?: string;
16
+ schemaPath?: string;
17
+ params?: unknown;
18
+ }
19
+ /**
20
+ * Synchronous, non-transforming data validation, independent of compilation.
21
+ * Success returns the original value; failure returns issues owned by that call.
22
+ * Implementations must preserve input identity and must not coerce, default,
23
+ * strip, or otherwise transform successful input. Standard Schema alone does
24
+ * not enforce these guarantees. Generic Standard Schema validators are not
25
+ * interchangeable unless they honor this stricter contract.
26
+ */
27
+ interface SynchronousDataValidator<T = unknown, Issue extends StandardSchemaV1.Issue = StandardSchemaV1.Issue> extends StandardSchemaV1<T, T> {
28
+ readonly '~standard': Omit<StandardSchemaV1.Props<T, T>, 'validate'> & {
29
+ readonly validate: (value: unknown) => StandardSchemaV1.SuccessResult<T> | {
30
+ readonly issues: readonly Issue[];
31
+ };
32
+ };
33
+ }
34
+ /**
35
+ * Lowest-level adapter interface.
36
+ *
37
+ * Contracts' embedded-schema checks establish shape only. An adapter must validate
38
+ * the schema against its supported dialect's meta-schema, reject unsupported
39
+ * dialects/keywords and unresolved references, then compile a synchronous
40
+ * validator. Any preparation failure must throw before returning a validator.
41
+ *
42
+ * Schemas without $schema use the adapter's documented default dialect.
43
+ * Implementations must not silently ignore unsupported validation constraints
44
+ * or fetch external references implicitly; references must already be resolvable.
45
+ */
46
+ interface JsonSchemaValidatorCompiler {
47
+ /**
48
+ * Validate and compile a schema, or throw. Never returns an async validator.
49
+ */
50
+ compile<T = unknown>(schema: JsonSchema): SynchronousDataValidator<T, SchemaValidationIssue>;
51
+ }
52
+ interface FunctionValidators {
53
+ readonly input: SynchronousDataValidator<Record<string, unknown>>;
54
+ readonly output?: SynchronousDataValidator;
55
+ }
56
+ interface StateTemplateValidators {
57
+ readonly state: SynchronousDataValidator<Record<string, unknown>>;
58
+ readonly functions: ReadonlyMap<string, FunctionValidators>;
59
+ }
60
+ /**
61
+ * Persistent identity within one storage namespace. A revision must identify
62
+ * immutable content; version distinguishes independently versioned templates.
63
+ * Namespace must distinguish tenants, drivers, and storage locations.
64
+ */
65
+ interface StateTemplateRevisionIdentity {
66
+ readonly namespace: string;
67
+ readonly templateId: string;
68
+ readonly templateVersion?: string;
69
+ readonly revision: string;
70
+ }
71
+ interface StateTemplatePreparationCacheOptions {
72
+ /**
73
+ * Maximum strongly retained revisions, using least-recently-used eviction.
74
+ * Defaults to 256. Zero disables revision retention, not weak identity caches.
75
+ */
76
+ readonly maxRevisions?: number;
77
+ }
78
+ type SchemaValidationTarget = 'initial-state' | 'input' | 'output' | 'state-before' | 'state-after';
79
+ //#endregion
80
+ //#region src/preparer.d.ts
81
+ /**
82
+ * Uncached preparation using one fixed compiler configuration.
83
+ * Templates and their schema graphs must remain immutable after preparation.
84
+ * This operation does not freeze or clone caller-owned data.
85
+ */
86
+ declare class StateTemplatePreparer {
87
+ private readonly schemaCompiler;
88
+ constructor(schemaCompiler: JsonSchemaValidatorCompiler);
89
+ prepare(definition: ReadonlyStateMachineTemplate): StateTemplateValidators;
90
+ /**
91
+ * Deliberately retain no revision association. This uncached policy accepts
92
+ * post-persistence binding notifications but does not inspect or cache them.
93
+ */
94
+ bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void;
95
+ }
96
+ //#endregion
97
+ //#region src/cached-preparer.d.ts
98
+ /**
99
+ * Compiler-scoped weak identity caches plus bounded LRU revision retention.
100
+ * Inputs must remain immutable and identities must never be reused for new content.
101
+ * Use a new preparer when compiler configuration changes.
102
+ */
103
+ declare class CachedStateTemplatePreparer {
104
+ private readonly schemaCache;
105
+ private readonly templateCache;
106
+ private readonly revisionCache;
107
+ private readonly compiler;
108
+ private readonly maxRevisions;
109
+ private readonly owned;
110
+ constructor(schemaCompiler: JsonSchemaValidatorCompiler, options?: StateTemplatePreparationCacheOptions);
111
+ get(identity: StateTemplateRevisionIdentity): StateTemplateValidators | undefined;
112
+ prepare(definition: ReadonlyStateMachineTemplate, identity?: StateTemplateRevisionIdentity): StateTemplateValidators;
113
+ /**
114
+ * Bind this preparer's complete result after a successful persistence operation.
115
+ * Results from another preparer/compiler configuration are rejected.
116
+ */
117
+ bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void;
118
+ invalidate(identity: StateTemplateRevisionIdentity): void;
119
+ /**
120
+ * Release strongly retained revisions; weak identity caches remain intact.
121
+ */
122
+ clearRevisionCache(): void;
123
+ }
124
+ //#endregion
125
+ //#region src/errors.d.ts
126
+ declare class SchemaValidationError extends Error {
127
+ readonly target: SchemaValidationTarget;
128
+ readonly issues: readonly SchemaValidationIssue[];
129
+ constructor(target: SchemaValidationTarget, issues: readonly SchemaValidationIssue[]);
130
+ }
131
+ //#endregion
132
+ //#region src/validation.d.ts
133
+ declare function assertSchema<T>(validator: SynchronousDataValidator<T>, value: unknown, target: SchemaValidationTarget): asserts value is T;
134
+ //#endregion
135
+ export { CachedStateTemplatePreparer, type FunctionValidators, type JsonSchemaValidatorCompiler, type SchemaTarget, SchemaValidationError, type SchemaValidationIssue, type SchemaValidationTarget, type StateTemplatePreparationCacheOptions, StateTemplatePreparer, type StateTemplateRevisionIdentity, type StateTemplateValidators, type SynchronousDataValidator, assertSchema };
136
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/preparer.ts","../src/cached-preparer.ts","../src/errors.ts","../src/validation.ts"],"mappings":";;;;;;KAMY;;;;;;;UAQK,8BAA8B,iBAAiB;EAC9D;EAEA;EAEA;;;;;;;;;;UAWe,yBACf,aACA,cAAc,iBAAiB,QAAQ,iBAAiB,eAChD,iBAAiB,GAAG;WACnB,aAAa,KAAK,iBAAiB,MAAM,GAAG;aAC1C,WAAW,mBAAmB,iBAAiB,cAAc;eAAgB,iBAAiB;;;;;;;;;;;;;;;;UAgB1F;;;;EAIf,QAAQ,aAAa,QAAQ,aAAa,yBAAyB,GAAG;;UAGvD;WACN,OAAO,yBAAyB;WAEhC,SAAS;;UAGH;WACN,OAAO,yBAAyB;WAEhC,WAAW,oBAAoB;;;;;;;UAQzB;WACN;WACA;WACA;WACA;;UAGM;;;;;WAKN;;KAGC;;;;;;;;cC5CC;mBACM;EAEL,YAAA,gBAAgB;EAIrB,QAAQ,YAAY,+BAA+B;;;;;EAWnD,KAAK,UAAU,+BAA+B,YAAY;;;;;;;;;cC5CtD;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,gBAAgB,6BAA6B,UAAS;EAiB3D,IAAI,UAAU,gCAAgC;EAW9C,QACL,YAAY,8BACZ,WAAW,gCACV;;;;;EAoBI,KAAK,UAAU,+BAA+B,YAAY;EAe1D,WAAW,UAAU;;;;EAOrB;;;;cCnGI,8BAA8B;WACzB,QAAQ;WACR,iBAAiB;EAErB,YAAA,QAAQ,wBAAwB,iBAAiB;;;;iBCH/C,aAAa,GAC3B,WAAW,yBAAyB,IACpC,gBACA,QAAQ,iCACC,SAAS"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{recordCounter as e,traceSynchronous as t}from"@onereach/state-machine-telemetry";function n(t,n){e(`@onereach/state-machine-validation`,`state_machine.preparation.cache.requests`,`{request}`,1,{cache:t,result:n?`hit`:`miss`})}function r(e,n,r){return t(`@onereach/state-machine-validation`,e,n,e===`schema.compile`?`schema_compilation_failed`:`template_preparation_failed`,r?{"state_machine.preparation.schema_target":r}:void 0)}var i=class extends Error{target;issues;constructor(e,t){super(`Schema validation failed: ${e}`),this.name=`SchemaValidationError`,this.target=e,this.issues=t.map(e=>({...e,...e.path!==void 0&&{path:e.path.map(e=>typeof e==`object`?{...e}:e)}}))}};function a(e,t,n){let r=e[`~standard`].validate(t);if(r.issues)throw new i(n,r.issues)}function o(e,t){return r(`template.prepare`,()=>{let n=t.compile(e.stateSchema,`state`);a(n,e.initialState,`initial-state`);let r=new Map;for(let n of e.functions)r.set(n.name,Object.freeze({input:t.compile(n.inputSchema,`input`),output:n.outputSchema?t.compile(n.outputSchema,`output`):void 0}));return Object.freeze({state:n,functions:c(r)})})}var s=class{schemaCompiler;constructor(e){this.schemaCompiler=e}prepare(e){return o(e,{compile:(e,t)=>r(`schema.compile`,()=>this.schemaCompiler.compile(e),t)})}bind(e,t){}};function c(e){let t={size:e.size,get:t=>e.get(t),has:t=>e.has(t),entries:()=>e.entries(),keys:()=>e.keys(),values:()=>e.values(),[Symbol.iterator]:()=>e[Symbol.iterator](),forEach(n,r){for(let[i,a]of e)n.call(r,a,i,t)}};return Object.freeze(t)}var l=class{schemaCache=new WeakMap;templateCache=new WeakMap;revisionCache=new Map;compiler;maxRevisions;owned=new WeakMap;constructor(e,t={}){if(this.maxRevisions=t.maxRevisions??256,!Number.isSafeInteger(this.maxRevisions)||this.maxRevisions<0)throw RangeError(`maxRevisions must be a non-negative safe integer`);let i=this.schemaCache;this.compiler={compile(t,a){let o=i.get(t);if(n(`schema`,o!==void 0),o)return o;let s=r(`schema.compile`,()=>e.compile(t),a);return i.set(t,s),s}}}get(e){let t=u(e),r=this.revisionCache.get(t);return n(`revision`,r!==void 0),r&&(this.revisionCache.delete(t),this.revisionCache.set(t,r)),r}prepare(e,t){if(t&&(t.templateId!==e.id||t.templateVersion!==e.version))throw Error(`Revision identity does not match the template`);let r=t?this.get(t):void 0;if(r)return r;let i=this.templateCache.get(e);return n(`template`,i!==void 0),i||(i=o(e,this.compiler),this.templateCache.set(e,i),this.owned.set(i,{id:e.id,version:e.version})),t&&this.bind(t,i),i}bind(e,t){let n=this.owned.get(t);if(!n)throw Error(`Cannot bind validators from another preparer`);if(e.templateId!==n.id||e.templateVersion!==n.version)throw Error(`Revision identity does not match the template`);let r=u(e);if(this.revisionCache.delete(r),this.maxRevisions!==0&&(this.revisionCache.set(r,t),this.revisionCache.size>this.maxRevisions)){let e=this.revisionCache.keys().next().value;e!==void 0&&this.revisionCache.delete(e)}}invalidate(e){this.revisionCache.delete(u(e))}clearRevisionCache(){this.revisionCache.clear()}};function u(e){return JSON.stringify([e.namespace,e.templateId,e.templateVersion,e.revision])}export{l as CachedStateTemplatePreparer,i as SchemaValidationError,s as StateTemplatePreparer,a as assertSchema};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/telemetry.ts","../src/errors.ts","../src/validation.ts","../src/preparer.ts","../src/cached-preparer.ts"],"sourcesContent":["import { recordCounter, traceSynchronous } from '@onereach/state-machine-telemetry';\n\nimport type { SchemaTarget } from './types.ts';\n\nexport function recordPreparationCache(cache: 'revision' | 'template' | 'schema', isHit: boolean): void {\n recordCounter('@onereach/state-machine-validation', 'state_machine.preparation.cache.requests', '{request}', 1, {\n cache,\n result: isHit ? 'hit' : 'miss',\n });\n}\n\n/**\n * Keep preparation synchronous and run it once even if host tracing fails.\n */\nexport function tracePreparation<T>(\n name: 'template.prepare' | 'schema.compile',\n prepare: () => T,\n target?: SchemaTarget,\n): T {\n return traceSynchronous(\n '@onereach/state-machine-validation',\n name,\n prepare,\n name === 'schema.compile' ? 'schema_compilation_failed' : 'template_preparation_failed',\n target ? { 'state_machine.preparation.schema_target': target } : undefined,\n );\n}\n","import type { SchemaValidationIssue, SchemaValidationTarget } from './types.ts';\n\nexport class SchemaValidationError extends Error {\n public readonly target: SchemaValidationTarget;\n public readonly issues: readonly SchemaValidationIssue[];\n\n constructor(target: SchemaValidationTarget, issues: readonly SchemaValidationIssue[]) {\n super(`Schema validation failed: ${target}`);\n\n this.name = 'SchemaValidationError';\n this.target = target;\n this.issues = issues.map((issue) => ({\n ...issue,\n ...(issue.path !== undefined && {\n path: issue.path.map((segment) => (typeof segment === 'object' ? { ...segment } : segment)),\n }),\n }));\n }\n}\n","import { SchemaValidationError } from './errors.ts';\nimport type { SynchronousDataValidator, SchemaValidationTarget } from './types.ts';\n\nexport function assertSchema<T>(\n validator: SynchronousDataValidator<T>,\n value: unknown,\n target: SchemaValidationTarget,\n): asserts value is T {\n const result = validator['~standard'].validate(value);\n if (result.issues) throw new SchemaValidationError(target, result.issues);\n}\n","import type { JsonSchema, ReadonlyStateMachineTemplate } from '@onereach/state-machine-contracts';\n\nimport { tracePreparation } from './telemetry.ts';\nimport type {\n FunctionValidators,\n StateTemplateValidators,\n JsonSchemaValidatorCompiler,\n StateTemplateRevisionIdentity,\n SynchronousDataValidator,\n SchemaValidationIssue,\n SchemaTarget,\n} from './types.ts';\nimport { assertSchema } from './validation.ts';\n\nexport interface PreparationCompiler {\n compile<T>(schema: JsonSchema, target: SchemaTarget): SynchronousDataValidator<T, SchemaValidationIssue>;\n}\n\n// Shared work boundary; cache-owning callers decide when compilation really runs.\nexport function prepareDefinition(\n definition: ReadonlyStateMachineTemplate,\n compiler: PreparationCompiler,\n): StateTemplateValidators {\n return tracePreparation('template.prepare', () => {\n const state = compiler.compile<Record<string, unknown>>(definition.stateSchema, 'state');\n // Reject invalid initial state before a template can be persisted.\n assertSchema(state, definition.initialState, 'initial-state');\n const functions = new Map<string, FunctionValidators>();\n for (const function_ of definition.functions) {\n functions.set(\n function_.name,\n Object.freeze({\n input: compiler.compile<Record<string, unknown>>(function_.inputSchema, 'input'),\n output: function_.outputSchema ? compiler.compile(function_.outputSchema, 'output') : undefined,\n }),\n );\n }\n return Object.freeze({ state, functions: readonlyFunctions(functions) });\n });\n}\n\n/**\n * Uncached preparation using one fixed compiler configuration.\n * Templates and their schema graphs must remain immutable after preparation.\n * This operation does not freeze or clone caller-owned data.\n */\nexport class StateTemplatePreparer {\n private readonly schemaCompiler: JsonSchemaValidatorCompiler;\n\n constructor(schemaCompiler: JsonSchemaValidatorCompiler) {\n this.schemaCompiler = schemaCompiler;\n }\n\n public prepare(definition: ReadonlyStateMachineTemplate): StateTemplateValidators {\n return prepareDefinition(definition, {\n compile: <T>(schema: JsonSchema, target: SchemaTarget) =>\n tracePreparation('schema.compile', () => this.schemaCompiler.compile<T>(schema), target),\n });\n }\n\n /**\n * Deliberately retain no revision association. This uncached policy accepts\n * post-persistence binding notifications but does not inspect or cache them.\n */\n public bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void {\n void identity;\n void validators;\n }\n}\n\n// Expose no mutable Map, including through forEach's third argument.\nfunction readonlyFunctions(functions: Map<string, FunctionValidators>): ReadonlyMap<string, FunctionValidators> {\n const view: ReadonlyMap<string, FunctionValidators> = {\n size: functions.size,\n get: (key) => functions.get(key),\n has: (key) => functions.has(key),\n entries: () => functions.entries(),\n keys: () => functions.keys(),\n values: () => functions.values(),\n [Symbol.iterator]: () => functions[Symbol.iterator](),\n forEach(callback, thisArgument) {\n for (const [key, value] of functions) callback.call(thisArgument, value, key, view);\n },\n };\n return Object.freeze(view);\n}\n","import type { JsonSchema, ReadonlyStateMachineTemplate } from '@onereach/state-machine-contracts';\n\nimport { prepareDefinition } from './preparer.ts';\nimport type { PreparationCompiler } from './preparer.ts';\nimport { recordPreparationCache, tracePreparation } from './telemetry.ts';\nimport type {\n SynchronousDataValidator,\n StateTemplateValidators,\n SchemaValidationIssue,\n JsonSchemaValidatorCompiler,\n StateTemplatePreparationCacheOptions,\n StateTemplateRevisionIdentity,\n SchemaTarget,\n} from './types.ts';\n\n/**\n * Compiler-scoped weak identity caches plus bounded LRU revision retention.\n * Inputs must remain immutable and identities must never be reused for new content.\n * Use a new preparer when compiler configuration changes.\n */\nexport class CachedStateTemplatePreparer {\n private readonly schemaCache = new WeakMap<object, SynchronousDataValidator<unknown, SchemaValidationIssue>>();\n private readonly templateCache = new WeakMap<ReadonlyStateMachineTemplate, StateTemplateValidators>();\n private readonly revisionCache = new Map<string, StateTemplateValidators>();\n private readonly compiler: PreparationCompiler;\n private readonly maxRevisions: number;\n private readonly owned = new WeakMap<StateTemplateValidators, { id: string; version?: string }>();\n\n constructor(schemaCompiler: JsonSchemaValidatorCompiler, options: StateTemplatePreparationCacheOptions = {}) {\n this.maxRevisions = options.maxRevisions ?? 256;\n if (!Number.isSafeInteger(this.maxRevisions) || this.maxRevisions < 0)\n throw new RangeError('maxRevisions must be a non-negative safe integer');\n const cache = this.schemaCache;\n this.compiler = {\n compile<T>(schema: JsonSchema, target: SchemaTarget): SynchronousDataValidator<T, SchemaValidationIssue> {\n const cached = cache.get(schema);\n recordPreparationCache('schema', cached !== undefined);\n if (cached) return cached as SynchronousDataValidator<T, SchemaValidationIssue>;\n const compiled = tracePreparation('schema.compile', () => schemaCompiler.compile<T>(schema), target);\n cache.set(schema, compiled);\n return compiled;\n },\n };\n }\n\n public get(identity: StateTemplateRevisionIdentity): StateTemplateValidators | undefined {\n const key = revisionKey(identity);\n const cached = this.revisionCache.get(key);\n recordPreparationCache('revision', cached !== undefined);\n if (cached) {\n this.revisionCache.delete(key);\n this.revisionCache.set(key, cached);\n }\n return cached;\n }\n\n public prepare(\n definition: ReadonlyStateMachineTemplate,\n identity?: StateTemplateRevisionIdentity,\n ): StateTemplateValidators {\n if (identity && (identity.templateId !== definition.id || identity.templateVersion !== definition.version))\n throw new Error('Revision identity does not match the template');\n const revisionCached = identity ? this.get(identity) : undefined;\n if (revisionCached) return revisionCached;\n let prepared = this.templateCache.get(definition);\n recordPreparationCache('template', prepared !== undefined);\n if (!prepared) {\n prepared = prepareDefinition(definition, this.compiler);\n this.templateCache.set(definition, prepared);\n this.owned.set(prepared, { id: definition.id, version: definition.version });\n }\n if (identity) this.bind(identity, prepared);\n return prepared;\n }\n\n /**\n * Bind this preparer's complete result after a successful persistence operation.\n * Results from another preparer/compiler configuration are rejected.\n */\n public bind(identity: StateTemplateRevisionIdentity, validators: StateTemplateValidators): void {\n const template = this.owned.get(validators);\n if (!template) throw new Error('Cannot bind validators from another preparer');\n if (identity.templateId !== template.id || identity.templateVersion !== template.version)\n throw new Error('Revision identity does not match the template');\n const key = revisionKey(identity);\n this.revisionCache.delete(key);\n if (this.maxRevisions === 0) return;\n this.revisionCache.set(key, validators);\n if (this.revisionCache.size > this.maxRevisions) {\n const oldest = this.revisionCache.keys().next().value;\n if (oldest !== undefined) this.revisionCache.delete(oldest);\n }\n }\n\n public invalidate(identity: StateTemplateRevisionIdentity): void {\n this.revisionCache.delete(revisionKey(identity));\n }\n\n /**\n * Release strongly retained revisions; weak identity caches remain intact.\n */\n public clearRevisionCache(): void {\n this.revisionCache.clear();\n }\n}\n\nfunction revisionKey(identity: StateTemplateRevisionIdentity): string {\n return JSON.stringify([identity.namespace, identity.templateId, identity.templateVersion, identity.revision]);\n}\n"],"mappings":"wFAIA,SAAgB,EAAuB,EAA2C,EAAsB,CACtG,EAAc,qCAAsC,2CAA4C,YAAa,EAAG,CAC9G,QACA,OAAQ,EAAQ,MAAQ,MAC1B,CAAC,CACH,CAKA,SAAgB,EACd,EACA,EACA,EACG,CACH,OAAO,EACL,qCACA,EACA,EACA,IAAS,iBAAmB,4BAA8B,8BAC1D,EAAS,CAAE,0CAA2C,CAAO,EAAI,IAAA,EACnE,CACF,CCxBA,IAAa,EAAb,cAA2C,KAAM,CAC/C,OACA,OAEA,YAAY,EAAgC,EAA0C,CACpF,MAAM,6BAA6B,GAAQ,EAE3C,KAAK,KAAO,wBACZ,KAAK,OAAS,EACd,KAAK,OAAS,EAAO,IAAK,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,OAPA,EAAuB,WAAY,IAAa,IAAA,EAAS,EACpD,IACH,EAAW,EAAkB,EAAY,KAAK,QAAQ,EACtD,KAAK,cAAc,IAAI,EAAY,CAAQ,EAC3C,KAAK,MAAM,IAAI,EAAU,CAAE,GAAI,EAAW,GAAI,QAAS,EAAW,OAAQ,CAAC,GAEzE,GAAU,KAAK,KAAK,EAAU,CAAQ,EACnC,CACT,CAMA,KAAY,EAAyC,EAA2C,CAC9F,IAAM,EAAW,KAAK,MAAM,IAAI,CAAU,EAC1C,GAAI,CAAC,EAAU,MAAU,MAAM,8CAA8C,EAC7E,GAAI,EAAS,aAAe,EAAS,IAAM,EAAS,kBAAoB,EAAS,QAC/E,MAAU,MAAM,+CAA+C,EACjE,IAAM,EAAM,EAAY,CAAQ,EAChC,QAAK,cAAc,OAAO,CAAG,EACzB,KAAK,eAAiB,IAC1B,KAAK,cAAc,IAAI,EAAK,CAAU,EAClC,KAAK,cAAc,KAAO,KAAK,cAAc,CAC/C,IAAM,EAAS,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAC5C,IAAW,IAAA,IAAW,KAAK,cAAc,OAAO,CAAM,CAC5D,CACF,CAEA,WAAkB,EAA+C,CAC/D,KAAK,cAAc,OAAO,EAAY,CAAQ,CAAC,CACjD,CAKA,oBAAkC,CAChC,KAAK,cAAc,MAAM,CAC3B,CACF,EAEA,SAAS,EAAY,EAAiD,CACpE,OAAO,KAAK,UAAU,CAAC,EAAS,UAAW,EAAS,WAAY,EAAS,gBAAiB,EAAS,QAAQ,CAAC,CAC9G"}
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@onereach/state-machine-validation",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-framework.4",
4
+ "description": "Engine-independent State Machine schema preparation and validation",
5
+ "author": "OneReach Development Team <dev.team@onereach.ai>",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "devDependencies": {
16
+ "@arethetypeswrong/core": "^0.18.5",
17
+ "@opentelemetry/context-async-hooks": "^2.12.1",
18
+ "@opentelemetry/sdk-metrics": "^2.12.1",
19
+ "@opentelemetry/sdk-trace-base": "^2.12.1",
20
+ "publint": "^0.3.24",
21
+ "tsdown": "^0.22.14",
22
+ "typescript": "^6.0.3"
23
+ },
24
+ "dependencies": {
25
+ "@onereach/state-machine-contracts": "1.0.0-framework.13",
26
+ "@onereach/state-machine-telemetry": "1.0.0-framework.2",
27
+ "@opentelemetry/api": "~1.9.1",
28
+ "@standard-schema/spec": "^1.1.0"
29
+ },
30
+ "exports": {
31
+ ".": "./dist/index.mjs",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown --config tsdown.config.mts",
36
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile .cache/typecheck/source.tsbuildinfo && tsc --noEmit -p test/tsconfig.json --incremental --tsBuildInfoFile .cache/typecheck/test.tsbuildinfo",
37
+ "test": "pnpm run unit",
38
+ "unit": "vitest run",
39
+ "unit:coverage": "vitest run --coverage"
40
+ }
6
41
  }