@20baht/validator 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # @20baht/validator
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
+ Server-side validation for [`@20baht/ui`](https://www.npmjs.com/package/@20baht/ui) form/workflow JSON — by re-running **the exact engine code the client runs**, at request time.
4
+
5
+ No JSON-Schema translation, no codegen, no drift: the schema your builder exported is the validator. Store new JSON, validation follows immediately — no recompile, no redeploy.
6
+
7
+ ```bash
8
+ bun add @20baht/validator # or npm i @20baht/validator
9
+ ```
10
+
11
+ ## Quick start (Elysia)
12
+
13
+ ```ts
14
+ import { Elysia, t } from 'elysia';
15
+ import { parseSchema, validateSubmission } from '@20baht/validator';
16
+
17
+ // any storage works — this is just JSON at rest
18
+ const schemas = new Map([['todo-form', parseSchema(todoFormJson)]]);
19
+
20
+ new Elysia()
21
+ .post(
22
+ '/api/submissions',
23
+ ({ body, status }) => {
24
+ const schema = schemas.get(body.id);
25
+ if (!schema) return status(404, { error: `unknown schema "${body.id}"` });
26
+
27
+ const result = validateSubmission(schema, body.data);
28
+ if (!result.valid) return status(422, { valid: false, errors: result.issues });
29
+
30
+ // result.data is canonical: defaults filled, hidden fields cleared —
31
+ // identical to what the client emits on baht-submit. Persist THIS.
32
+ return status(201, { valid: true, data: result.data });
33
+ },
34
+ // one endpoint serves every schema — data stays open on purpose
35
+ { body: t.Object({ id: t.String(), data: t.Any() }) },
36
+ )
37
+ .listen(3001);
38
+ ```
39
+
40
+ A request that bypasses your frontend gets the same verdict the frontend would have shown, message for message:
41
+
42
+ ```
43
+ POST /api/submissions {"id":"todo-form","data":{"title":"ab"}}
44
+ → 422 {"errors":[{"ref":"title","message":"Must be at least 3 characters"}]}
45
+ ```
46
+
47
+ ## Elysia routes: `@20baht/validator/elysia`
48
+
49
+ For a route per form, the plugin adds a `validate` route option: the body is validated before
50
+ the handler runs, a refused body answers `422 { issues }`, and the handler receives the
51
+ canonical data as `validated`. `elysia` (>=1.4) is an optional peer, imported by this entry
52
+ only.
53
+
54
+ ```ts
55
+ import { Elysia, t } from 'elysia';
56
+ import { bahtValidator } from '@20baht/validator/elysia';
57
+
58
+ new Elysia()
59
+ .use(bahtValidator({ registry, verify: true }))
60
+ .post('/images', ({ validated }) => images.import(validated), {
61
+ validate: importForm,
62
+ body: t.Object({ name: t.String(), url: t.String() }), // still yours, for OpenAPI
63
+ })
64
+ // a lone form with rules (a one-form workflow): refs and data are the form's own
65
+ .post('/rules', ({ validated }) => rules.add(validated), {
66
+ validate: { schema: ruleWorkflow, form: 'Rule' },
67
+ });
68
+ ```
69
+
70
+ `bahtValidator(options)` takes `{ registry?, locale?, strict?, verify? }`; `verify: true` also
71
+ awaits `verifyOptions` and `verifyReferences`. The `t` body schema is not derived from the form.
72
+
73
+ ## Compatibility
74
+
75
+ Peers on [`@20baht/engine`](https://www.npmjs.com/package/@20baht/engine) of the same minor (the engine and the `FieldType` union come from there; see `peerDependencies`). It no longer peers on `@20baht/ui`, so a server installs no Lit. `@20baht/ui/engine` re-exports the same package: types and `setLocale` imported from either are the same ones. The `@20baht/validator/elysia` entry also peers, optionally, on `elysia` **>=1.4 <2**. All bahtui libraries except the stickers share one version number; keep them equal.
76
+
77
+ ## What it enforces
78
+
79
+ - Every declarative validator of the field descriptors: `required`, `min_length`, `max_length`, `min`, `max`, `pattern` (never run on more than 10000 characters), `email`, `url` (`schemes` checked by `parseSchema`), and `custom` (via a `Registry`; called as `(value, data, field)`, as on the client).
80
+ - **Dynamic options** (`options_from`) are not checked by `validateSubmission` (the options are async); `await verifyOptions(schema, result.data, registry)` checks them with the same fetchers the client calls:
81
+
82
+ ```ts
83
+ const result = validateSubmission(schema, body, registry);
84
+ const issues = [
85
+ ...result.issues,
86
+ ...(await verifyOptions(schema, result.data, registry)),
87
+ ...(await verifyReferences(schema, result.data, registry)),
88
+ ];
89
+ ```
90
+
91
+ Both async checks take `options` `{ form?: string }`, like `validateSubmission` (see below).
92
+ - Value **shape** per field type before any validator runs — a `password`/`text` must be a string, a `number` a finite number, a `dropdown` one of its option keys — so `{"$gt":""}` from a raw API call is rejected, not treated as "non-empty".
93
+ - **Workflow rules first** (`evaluate` from `@20baht/engine`): fields hidden by rules are excluded and smuggled values are cleared; `required` derived from rules is enforced; `setValue` results are computed.
94
+ - Approval steps: a `decision` must be present, the comment must be a string, and the comment policy (`required` / `requireOnReject`) is honored (a blank or zero-width comment does not count).
95
+ - **Canonical data holds only what the UI could emit:** repeater rows keep their declared columns only (a row with its own `__proto__` key is rejected), file values must be uploaded refs `{ name, size, url, type? }` with an `http(s)` or relative `url` and keep only those keys, `-0` is stored as `0`.
96
+ - **Strict by default (0.5.0):** a `custom` validator or `submit` script with no own entry in the registry, and a script that throws, are issues instead of being skipped. Pass `{ strict: false }` as the fifth argument to get the client's warn-and-skip behaviour (previews, docs tooling).
97
+ - **Client `submit` scripts** (spec 01 §14): re-run headlessly with the same `registry.scripts` — `g.setValue()` lands in canonical data, `g.addErrorMessage()` becomes an issue on `$` (`form_name.$` in a workflow), returning `false` blocks. `load` / `change` scripts are UI-only and never run here, so a field a client script hides is still validated: keep submit-relevant logic in rules or validators. `parseSchema` rejects a `scripts[]` entry with an unknown `on`, no `handler`, or a `change` hook on a field that does not exist.
98
+
99
+ ## API
100
+
101
+ | export | what it does |
102
+ | --- | --- |
103
+ | `validateSubmission(schema, data, registry?, locale?, options?)` | dispatches on schema kind — the single server entry point |
104
+ | `validateFormData(form, data, registry?, locale?, options?)` | mirrors `<baht-form>.validate()` for a standalone form |
105
+ | `validateWorkflowData(workflow, data, registry?, locale?, options?)` | evaluates rules, then validates every visible form |
106
+
107
+ `options` is `{ strict?: boolean; form?: string; context?: NestedData }`. `strict` defaults to `true` (see above).
108
+ `form` (workflows only) validates `data` as the flat body of that one form of the workflow,
109
+ rules applied: issue refs are field keys and `data` is that form's own canonical data. It is
110
+ how a lone form with rules is validated: the form is a one-form workflow (rendered by
111
+ `<baht-workflow chrome="none">`):
112
+
113
+ ```ts
114
+ const result = validateSubmission(ruleWorkflow, body, registry, undefined, { form: 'Rule' });
115
+ // result.issues: [{ ref: 'portMin', message: 'This field is required' }]
116
+ // result.data: { protocol: 'tcp', portMin: null }
117
+ ```
118
+
119
+ **One step of a run that lives on the server.** When a workflow is filled one step at a time, by
120
+ different people over days (a request, then an approver's review), validate each step as it is
121
+ submitted with `form`, and pass what is already stored for the other steps as `context`. The rules
122
+ read it (a condition on `Review.scanned` sees the review); it is not validated and not returned:
123
+
124
+ ```ts
125
+ const result = validateSubmission(changeWorkflow, body, registry, undefined, {
126
+ form: 'Request',
127
+ context: { Review: stored.review }, // the other steps' data, as `{ formName: { … } }`
128
+ });
129
+ ```
130
+
131
+ In the browser, `stepFieldStates(workflow, 'Request', { Request: data, Review: stored.review })`
132
+ from `@20baht/engine` gives `<baht-form>.fieldStates` for the same step, from the same rules.
133
+ `context` is not a `validate` option of the Elysia macro: it is per request, so call
134
+ `validateSubmission` in the handler.
135
+
136
+ | `parseSchema(json)` | structural gate for storing builder output (throws on bad input) |
137
+ | `verifyReferences(schema, data, registry?, options?)` | async: resolves every `reference` field id through `registry.references[name].resolve` and returns issues for records that do not exist (call after `validateSubmission`). `options`: `{ form?, locale? }`; the messages are read when the call starts, so a catalog switched while a lookup is awaited does not change them |
138
+ | `verifyOptions(schema, data, registry?, options?)` | async: calls `registry.options[name](data)` for every `options_from` field (dropdown, radio, multiselect, `tags` with `allow_new: false`, repeater columns too) and returns issues for keys the fetcher does not offer, an unknown source, or a fetcher that fails (call after `validateSubmission`) |
139
+ | `isFormDefinition` / `isWorkflowDefinition` | schema kind guards |
140
+
141
+ All results are `{ valid, issues, data }`; issues are `{ ref, message }` where `ref` is the field key (forms) or `form_name.key` (workflows).
@@ -0,0 +1,51 @@
1
+ import { type FieldDescriptor, type FormDefinition, type NestedData, type WorkflowDefinition } from '@20baht/engine';
2
+ export type SchemaDefinition = FormDefinition | WorkflowDefinition;
3
+ /** One violation. `ref` is the field key for forms, `form_name.key` for workflows. */
4
+ export interface ValidationIssue {
5
+ ref: string;
6
+ message: string;
7
+ }
8
+ /**
9
+ * `strict` (default true) fails closed on anything the server cannot check:
10
+ * a `custom` validator or a `submit` script with no registry entry, and a
11
+ * script that throws, each become an issue. `strict: false` restores the
12
+ * client's warn-and-skip behaviour for callers that only preview.
13
+ */
14
+ export interface ValidateOptions {
15
+ strict?: boolean;
16
+ /**
17
+ * Workflows only (ignored for a form): validate `data` as the flat body of this one
18
+ * form of the workflow, the workflow's rules applied. Issue refs are field keys and
19
+ * `data` is that form's canonical data, exactly as for `validateFormData`. Meant for a
20
+ * lone form with rules (a one-form workflow, rendered by `<baht-workflow chrome="none">`),
21
+ * or one step of a longer run filled one step at a time: the other forms are never
22
+ * validated, and read as their defaults unless `context` gives their data.
23
+ */
24
+ form?: string;
25
+ /**
26
+ * With `form`: what is known of the other forms, `{ formName: { … } }`. The rules read it
27
+ * (a condition on `Review.scanned` sees the review's data) but it is not validated and not
28
+ * returned; an entry for `form` itself is ignored, the body is that form's data. The engine's
29
+ * `stepFieldStates(workflow, form, data)` gives the browser the same field states.
30
+ */
31
+ context?: NestedData;
32
+ }
33
+ export interface ValidationResult {
34
+ valid: boolean;
35
+ issues: ValidationIssue[];
36
+ /**
37
+ * Canonical data the server should persist: input overlaid on field
38
+ * defaults; for workflows also with hidden fields cleared and setValue
39
+ * rules applied — identical to what the client emits on `baht-submit`.
40
+ */
41
+ data: Record<string, unknown> | NestedData;
42
+ }
43
+ /** `fn` in `locale`'s catalog, the previous one put back after: the engine's, shared with the form session. */
44
+ export { withLocale } from '@20baht/engine';
45
+ /** Static blocks (`label`, `section`): no value, never in the payload, never validated. */
46
+ export declare function isStatic(field: FieldDescriptor): boolean;
47
+ export declare function isWorkflowDefinition(schema: unknown): schema is WorkflowDefinition;
48
+ export declare function isFormDefinition(schema: unknown): schema is FormDefinition;
49
+ export declare function isRecord(v: unknown): v is Record<string, unknown>;
50
+ export declare function sorted(fields: FieldDescriptor[]): FieldDescriptor[];
51
+ export declare function ownEntry<T>(map: Record<string, T> | undefined, name: string): T | undefined;
package/dist/common.js ADDED
@@ -0,0 +1,29 @@
1
+ import {} from '@20baht/engine';
2
+ /** `fn` in `locale`'s catalog, the previous one put back after: the engine's, shared with the form session. */
3
+ export { withLocale } from '@20baht/engine';
4
+ /** Static blocks (`label`, `section`): no value, never in the payload, never validated. */
5
+ export function isStatic(field) {
6
+ return field.type === 'label' || field.type === 'section';
7
+ }
8
+ export function isWorkflowDefinition(schema) {
9
+ return (isRecord(schema) &&
10
+ typeof schema.workflow_id === 'string' &&
11
+ Array.isArray(schema.forms) &&
12
+ Array.isArray(schema.rules));
13
+ }
14
+ export function isFormDefinition(schema) {
15
+ return (isRecord(schema) &&
16
+ !isWorkflowDefinition(schema) &&
17
+ typeof schema.form_id === 'string' &&
18
+ typeof schema.form_name === 'string' &&
19
+ Array.isArray(schema.fields));
20
+ }
21
+ export function isRecord(v) {
22
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
23
+ }
24
+ export function sorted(fields) {
25
+ return [...fields].sort((a, b) => a.order - b.order);
26
+ }
27
+ export function ownEntry(map, name) {
28
+ return map && Object.hasOwn(map, name) ? map[name] : undefined;
29
+ }
@@ -0,0 +1,217 @@
1
+ import { Elysia } from 'elysia';
2
+ import { type SchemaDefinition, type ValidationIssue } from './index.js';
3
+ import type { Locale, Registry } from '@20baht/engine';
4
+ /** What `bahtValidator()` is configured with, once per app. */
5
+ export interface ElysiaValidatorOptions {
6
+ /** The registry the client uses: custom validators, submit scripts, option fetchers, lookups. */
7
+ registry?: Registry;
8
+ /** Locale of the issue messages. Unset: the engine's current catalog. */
9
+ locale?: Locale;
10
+ /** `false`: warn and skip unregistered custom validators / submit scripts. Default true. */
11
+ strict?: boolean;
12
+ /**
13
+ * Also `await verifyOptions` and `verifyReferences` (the async checks: `options_from`
14
+ * membership and record existence) before the handler. Default false.
15
+ */
16
+ verify?: boolean;
17
+ }
18
+ /**
19
+ * The `validate` route option: a form or workflow schema, or `{ schema, form }` to validate
20
+ * the flat body of one form of a workflow (a lone form with rules), refs as field keys.
21
+ */
22
+ export type ValidateTarget = SchemaDefinition | {
23
+ schema: SchemaDefinition;
24
+ form: string;
25
+ };
26
+ /** The 422 answer's body. */
27
+ export interface ValidationFailure {
28
+ issues: ValidationIssue[];
29
+ }
30
+ /**
31
+ * An Elysia plugin adding the `validate` route option. With it, the route validates its body
32
+ * with @20baht/validator before the handler runs: a refused body answers
33
+ * `422 { issues }`, a valid one reaches the handler as `validated` (canonical data). Routes
34
+ * without the option are untouched. The route's own `body` schema (for OpenAPI) still applies
35
+ * first, if it has one.
36
+ */
37
+ export declare function bahtValidator(options?: ElysiaValidatorOptions): Elysia<"", {
38
+ decorator: {};
39
+ store: {};
40
+ derive: {};
41
+ resolve: {};
42
+ }, {
43
+ typebox: {};
44
+ error: {};
45
+ }, {
46
+ schema: {};
47
+ standaloneSchema: {};
48
+ macro: Partial<{
49
+ readonly validate: ValidateTarget;
50
+ }>;
51
+ macroFn: {
52
+ readonly validate: (target: ValidateTarget) => {
53
+ readonly resolve: ({ body, status }: {
54
+ body: unknown;
55
+ query: Record<string, string>;
56
+ params: {};
57
+ headers: Record<string, string | undefined>;
58
+ cookie: Record<string, import("elysia").Cookie<unknown>>;
59
+ server: import("elysia/universal/server").Server | null;
60
+ redirect: import("elysia").redirect;
61
+ set: {
62
+ headers: import("elysia").HTTPHeaders;
63
+ status?: number | keyof import("elysia").StatusMap;
64
+ redirect?: string;
65
+ cookie?: Record<string, import("elysia/cookies").ElysiaCookie>;
66
+ };
67
+ path: string;
68
+ route: string;
69
+ request: Request;
70
+ store: {};
71
+ status: <const Code extends number | keyof import("elysia").StatusMap, const T = Code extends 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 300 | 301 | 302 | 303 | 304 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
72
+ readonly 100: "Continue";
73
+ readonly 101: "Switching Protocols";
74
+ readonly 102: "Processing";
75
+ readonly 103: "Early Hints";
76
+ readonly 200: "OK";
77
+ readonly 201: "Created";
78
+ readonly 202: "Accepted";
79
+ readonly 203: "Non-Authoritative Information";
80
+ readonly 204: "No Content";
81
+ readonly 205: "Reset Content";
82
+ readonly 206: "Partial Content";
83
+ readonly 207: "Multi-Status";
84
+ readonly 208: "Already Reported";
85
+ readonly 300: "Multiple Choices";
86
+ readonly 301: "Moved Permanently";
87
+ readonly 302: "Found";
88
+ readonly 303: "See Other";
89
+ readonly 304: "Not Modified";
90
+ readonly 307: "Temporary Redirect";
91
+ readonly 308: "Permanent Redirect";
92
+ readonly 400: "Bad Request";
93
+ readonly 401: "Unauthorized";
94
+ readonly 402: "Payment Required";
95
+ readonly 403: "Forbidden";
96
+ readonly 404: "Not Found";
97
+ readonly 405: "Method Not Allowed";
98
+ readonly 406: "Not Acceptable";
99
+ readonly 407: "Proxy Authentication Required";
100
+ readonly 408: "Request Timeout";
101
+ readonly 409: "Conflict";
102
+ readonly 410: "Gone";
103
+ readonly 411: "Length Required";
104
+ readonly 412: "Precondition Failed";
105
+ readonly 413: "Payload Too Large";
106
+ readonly 414: "URI Too Long";
107
+ readonly 415: "Unsupported Media Type";
108
+ readonly 416: "Range Not Satisfiable";
109
+ readonly 417: "Expectation Failed";
110
+ readonly 418: "I'm a teapot";
111
+ readonly 420: "Enhance Your Calm";
112
+ readonly 421: "Misdirected Request";
113
+ readonly 422: "Unprocessable Content";
114
+ readonly 423: "Locked";
115
+ readonly 424: "Failed Dependency";
116
+ readonly 425: "Too Early";
117
+ readonly 426: "Upgrade Required";
118
+ readonly 428: "Precondition Required";
119
+ readonly 429: "Too Many Requests";
120
+ readonly 431: "Request Header Fields Too Large";
121
+ readonly 451: "Unavailable For Legal Reasons";
122
+ readonly 500: "Internal Server Error";
123
+ readonly 501: "Not Implemented";
124
+ readonly 502: "Bad Gateway";
125
+ readonly 503: "Service Unavailable";
126
+ readonly 504: "Gateway Timeout";
127
+ readonly 505: "HTTP Version Not Supported";
128
+ readonly 506: "Variant Also Negotiates";
129
+ readonly 507: "Insufficient Storage";
130
+ readonly 508: "Loop Detected";
131
+ readonly 510: "Not Extended";
132
+ readonly 511: "Network Authentication Required";
133
+ }[Code] : Code>(code: Code, response?: T) => import("elysia").ElysiaCustomStatusResponse<Code, T, Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Enhance Your Calm" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
134
+ readonly Continue: 100;
135
+ readonly "Switching Protocols": 101;
136
+ readonly Processing: 102;
137
+ readonly "Early Hints": 103;
138
+ readonly OK: 200;
139
+ readonly Created: 201;
140
+ readonly Accepted: 202;
141
+ readonly "Non-Authoritative Information": 203;
142
+ readonly "No Content": 204;
143
+ readonly "Reset Content": 205;
144
+ readonly "Partial Content": 206;
145
+ readonly "Multi-Status": 207;
146
+ readonly "Already Reported": 208;
147
+ readonly "Multiple Choices": 300;
148
+ readonly "Moved Permanently": 301;
149
+ readonly Found: 302;
150
+ readonly "See Other": 303;
151
+ readonly "Not Modified": 304;
152
+ readonly "Temporary Redirect": 307;
153
+ readonly "Permanent Redirect": 308;
154
+ readonly "Bad Request": 400;
155
+ readonly Unauthorized: 401;
156
+ readonly "Payment Required": 402;
157
+ readonly Forbidden: 403;
158
+ readonly "Not Found": 404;
159
+ readonly "Method Not Allowed": 405;
160
+ readonly "Not Acceptable": 406;
161
+ readonly "Proxy Authentication Required": 407;
162
+ readonly "Request Timeout": 408;
163
+ readonly Conflict: 409;
164
+ readonly Gone: 410;
165
+ readonly "Length Required": 411;
166
+ readonly "Precondition Failed": 412;
167
+ readonly "Payload Too Large": 413;
168
+ readonly "URI Too Long": 414;
169
+ readonly "Unsupported Media Type": 415;
170
+ readonly "Range Not Satisfiable": 416;
171
+ readonly "Expectation Failed": 417;
172
+ readonly "I'm a teapot": 418;
173
+ readonly "Enhance Your Calm": 420;
174
+ readonly "Misdirected Request": 421;
175
+ readonly "Unprocessable Content": 422;
176
+ readonly Locked: 423;
177
+ readonly "Failed Dependency": 424;
178
+ readonly "Too Early": 425;
179
+ readonly "Upgrade Required": 426;
180
+ readonly "Precondition Required": 428;
181
+ readonly "Too Many Requests": 429;
182
+ readonly "Request Header Fields Too Large": 431;
183
+ readonly "Unavailable For Legal Reasons": 451;
184
+ readonly "Internal Server Error": 500;
185
+ readonly "Not Implemented": 501;
186
+ readonly "Bad Gateway": 502;
187
+ readonly "Service Unavailable": 503;
188
+ readonly "Gateway Timeout": 504;
189
+ readonly "HTTP Version Not Supported": 505;
190
+ readonly "Variant Also Negotiates": 506;
191
+ readonly "Insufficient Storage": 507;
192
+ readonly "Loop Detected": 508;
193
+ readonly "Not Extended": 510;
194
+ readonly "Network Authentication Required": 511;
195
+ }[Code] : Code>;
196
+ }) => Promise<import("elysia").ElysiaCustomStatusResponse<422, {
197
+ issues: ValidationIssue[];
198
+ }, 422> | {
199
+ validated: Record<string, unknown>;
200
+ }>;
201
+ };
202
+ };
203
+ parser: {};
204
+ response: {};
205
+ }, {}, {
206
+ derive: {};
207
+ resolve: {};
208
+ schema: {};
209
+ standaloneSchema: {};
210
+ response: {};
211
+ }, {
212
+ derive: {};
213
+ resolve: {};
214
+ schema: {};
215
+ standaloneSchema: {};
216
+ response: {};
217
+ }>;
package/dist/elysia.js ADDED
@@ -0,0 +1,56 @@
1
+ // ---------------------------------------------------------------------------
2
+ // @20baht/validator/elysia — the validate-or-422 step every write route repeats, as an
3
+ // Elysia macro. `elysia` is an optional peer: only this entry imports it.
4
+ //
5
+ // new Elysia()
6
+ // .use(bahtValidator({ registry }))
7
+ // .post('/images', ({ validated }) => save(validated), { validate: importForm })
8
+ //
9
+ // A body the form refuses never reaches the handler: the route answers
10
+ // `422 { issues: [{ ref, message }] }`. The handler gets `validated`, the canonical data
11
+ // (defaults filled, hidden fields dropped): use it, never the raw `body`.
12
+ // ---------------------------------------------------------------------------
13
+ import { Elysia } from 'elysia';
14
+ import { validateSubmission, verifyOptions, verifyReferences, } from './index.js';
15
+ function split(target) {
16
+ return 'schema' in target
17
+ ? { schema: target.schema, form: target.form }
18
+ : { schema: target, form: undefined };
19
+ }
20
+ /** Validate `body` the way the route option does; `issues` empty when it passes. */
21
+ async function check(target, body, options) {
22
+ const { schema, form } = split(target);
23
+ const { registry, locale, strict, verify } = options;
24
+ const result = validateSubmission(schema, body, registry, locale, {
25
+ ...(strict === undefined ? {} : { strict }),
26
+ ...(form === undefined ? {} : { form }),
27
+ });
28
+ const issues = [...result.issues];
29
+ if (result.valid && verify) {
30
+ const scope = {
31
+ ...(form === undefined ? {} : { form }),
32
+ ...(locale === undefined ? {} : { locale }),
33
+ };
34
+ issues.push(...(await verifyOptions(schema, result.data, registry, scope)), ...(await verifyReferences(schema, result.data, registry, scope)));
35
+ }
36
+ return { data: result.data, issues };
37
+ }
38
+ /**
39
+ * An Elysia plugin adding the `validate` route option. With it, the route validates its body
40
+ * with @20baht/validator before the handler runs: a refused body answers
41
+ * `422 { issues }`, a valid one reaches the handler as `validated` (canonical data). Routes
42
+ * without the option are untouched. The route's own `body` schema (for OpenAPI) still applies
43
+ * first, if it has one.
44
+ */
45
+ export function bahtValidator(options = {}) {
46
+ return new Elysia({ name: '@20baht/validator', seed: options }).macro({
47
+ validate: (target) => ({
48
+ async resolve({ body, status }) {
49
+ const { data, issues } = await check(target, body, options);
50
+ if (issues.length > 0)
51
+ return status(422, { issues });
52
+ return { validated: data };
53
+ },
54
+ }),
55
+ });
56
+ }
@@ -0,0 +1,9 @@
1
+ export type { SchemaDefinition, ValidateOptions, ValidationIssue, ValidationResult, } from './common.js';
2
+ export { isFormDefinition, isWorkflowDefinition } from './common.js';
3
+ export { validateFormData, validateSubmission, validateWorkflowData } from './submission.js';
4
+ export { verifyOptions, verifyReferences, type VerifyOptions } from './verify.js';
5
+ export { parseSchema } from './schema.js';
6
+ import { applyFlags, approvalFields, defaultValue, evaluate, resolveViewFields, setLocale, validateField, type FormDefinition, type NestedData, type Registry, type WorkflowDefinition, type WorkflowForm } from '@20baht/engine';
7
+ export { applyFlags, approvalFields, defaultValue, evaluate, resolveViewFields, setLocale, validateField, };
8
+ export type { FormDefinition, NestedData, Registry, WorkflowDefinition, WorkflowForm };
9
+ export type { FeatureFlags, FormViewSpec, Locale, MessageCatalog } from '@20baht/engine';
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ // ---------------------------------------------------------------------------
2
+ // @20baht/validator — run the client's validation on the server, at runtime.
3
+ //
4
+ // The builder exports plain JSON (FormDefinition / WorkflowDefinition). The
5
+ // client validates it with @20baht/ui/engine (`evaluate` + `validateField`).
6
+ // This package feeds the same JSON through the same engine functions, so a
7
+ // request that bypasses the frontend hits the exact same rules — no codegen,
8
+ // no recompile: swap the stored JSON and validation follows.
9
+ //
10
+ // Unlike the client, this package sits on a trust boundary: `input` is an
11
+ // untrusted request body and the schema may predate parseSchema hardening.
12
+ // Reads are own-property only, prototype-writing keys are rejected, and
13
+ // every value must have the shape the UI control could actually emit before
14
+ // the authored validators run.
15
+ export { isFormDefinition, isWorkflowDefinition } from './common.js';
16
+ export { validateFormData, validateSubmission, validateWorkflowData } from './submission.js';
17
+ export { verifyOptions, verifyReferences } from './verify.js';
18
+ export { parseSchema } from './schema.js';
19
+ import { applyFlags, approvalFields, defaultValue, evaluate, resolveViewFields, setLocale, validateField, } from '@20baht/engine';
20
+ // Re-exported so servers can type stores and registries without a direct
21
+ // dependency on @20baht/ui. `setLocale` localizes the issues this package
22
+ // emits (same catalog the client renders). `applyFlags` resolves feature
23
+ // flags server-side — validate flag-gated schemas as
24
+ // `validateSubmission(applyFlags(schema, flags), data)`.
25
+ export { applyFlags, approvalFields, defaultValue, evaluate, resolveViewFields, setLocale, validateField, };
@@ -0,0 +1,12 @@
1
+ import { type SchemaDefinition } from './common.js';
2
+ /**
3
+ * Structural gate for storing builder output — the same checks the builder's
4
+ * Import applies, so the server only ever stores schemas the client could
5
+ * render. Throws with a human-readable message on bad input.
6
+ *
7
+ * Beyond shape it validates referential integrity (rule targets, condition
8
+ * refs, transition endpoints, on_reject.goto) and compiles every `pattern`
9
+ * validator, so authoring defects surface at store time — not as a 500 or a
10
+ * submission that can never pass.
11
+ */
12
+ export declare function parseSchema(json: unknown): SchemaDefinition;