hyperschema-ts 0.0.0 → 0.1.0
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 +201 -0
- package/README.md +229 -0
- package/index.cjs +37 -0
- package/index.d.ts +25 -0
- package/index.mjs +7 -0
- package/lib/codegen.js +171 -0
- package/lib/validate.js +274 -0
- package/package.json +67 -1
- package/validation.cjs +38 -0
- package/validation.d.ts +56 -0
- package/validation.mjs +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# hyperschema-ts
|
|
2
|
+
|
|
3
|
+
Generate TypeScript types from a [Hyperschema](https://github.com/holepunchto/hyperschema).
|
|
4
|
+
|
|
5
|
+
Point it at the same `schema` instance you pass to `Hyperschema.toDisk`, and it writes a `.d.ts` file of `interface`/`type` declarations matching your structs, enums, aliases, arrays and records. You then `import` those types into your app to get static typing over the objects you encode and decode.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install hyperschema-ts
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
const Hyperschema = require('hyperschema')
|
|
17
|
+
const HyperschemaTS = require('hyperschema-ts')
|
|
18
|
+
|
|
19
|
+
const schema = Hyperschema.from('./schema')
|
|
20
|
+
const ns = schema.namespace('example')
|
|
21
|
+
|
|
22
|
+
ns.register({
|
|
23
|
+
name: 'request',
|
|
24
|
+
fields: [
|
|
25
|
+
{ name: 'id', type: 'uint', required: true },
|
|
26
|
+
{ name: 'name', type: 'string', required: true },
|
|
27
|
+
{ name: 'tags', type: 'string', array: true }
|
|
28
|
+
]
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
// Write the compact-encoding definitions (schema.json + index.js)
|
|
32
|
+
Hyperschema.toDisk(schema)
|
|
33
|
+
|
|
34
|
+
// Write the matching TypeScript declarations (types.d.ts)
|
|
35
|
+
HyperschemaTS.toDisk(schema)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
This writes `./schema/types.d.ts`:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// This file is autogenerated by hyperschema-ts
|
|
42
|
+
// Schema version: 1
|
|
43
|
+
// Do not edit manually.
|
|
44
|
+
|
|
45
|
+
export interface ExampleRequest {
|
|
46
|
+
id: number
|
|
47
|
+
name: string
|
|
48
|
+
tags?: string[] | null
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
which you import as type-only:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import type { ExampleRequest } from './schema/types'
|
|
56
|
+
|
|
57
|
+
const req: ExampleRequest = { id: 1, name: 'a' }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
> On `node16`/`nodenext` resolution, import without an extension as above (a `.d.ts` has no runtime counterpart to point a `.js` specifier at). On `bundler` or classic resolution it resolves either way.
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
### `HyperschemaTS.toDisk(schema, [dir], [options])`
|
|
65
|
+
|
|
66
|
+
Writes the generated declarations to disk. Mirrors `Hyperschema.toDisk`:
|
|
67
|
+
|
|
68
|
+
- `dir` defaults to `schema.dir` (the directory the schema was loaded from).
|
|
69
|
+
- Output file defaults to `<dir>/types.d.ts`.
|
|
70
|
+
|
|
71
|
+
Returns the path it wrote.
|
|
72
|
+
|
|
73
|
+
> The output is pure type declarations, so it's emitted as a `.d.ts`. The default name avoids `index.d.ts` on purpose: that would sit next to hyperschema's generated `index.js` and TypeScript would treat it as the declarations _for_ that module (which actually exports `resolveStruct`/`version`, not these types).
|
|
74
|
+
|
|
75
|
+
### `HyperschemaTS.toCode(schema, [options])`
|
|
76
|
+
|
|
77
|
+
Returns the generated declarations as a string instead of writing them.
|
|
78
|
+
|
|
79
|
+
### `HyperschemaTS.typeName(fqn)`
|
|
80
|
+
|
|
81
|
+
Converts a fully-qualified hyperschema name to its generated TS type name, e.g. `@example/my-struct` → `ExampleMyStruct`.
|
|
82
|
+
|
|
83
|
+
### Options
|
|
84
|
+
|
|
85
|
+
- `filename` — override the output path (otherwise `<dir>/types.d.ts`).
|
|
86
|
+
- `externals` — a map of fully-qualified external type name → TS expression to substitute for it (external types default to `unknown`).
|
|
87
|
+
|
|
88
|
+
## Type mapping
|
|
89
|
+
|
|
90
|
+
| hyperschema | TypeScript |
|
|
91
|
+
| ------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
92
|
+
| `uint*`, `int*`, `float32/64`, `port`, `lexint` | `number` |
|
|
93
|
+
| `bigint`, `biguint64`, `bigint64` | `bigint` |
|
|
94
|
+
| `string`, `utf8`, `ascii`, `hex` | `string` |
|
|
95
|
+
| `ip`, `ipv4`, `ipv6` | `string` |
|
|
96
|
+
| `ipAddress`, `ipv4Address`, `ipv6Address` | `{ host: string; family?: number; port: number }` |
|
|
97
|
+
| `bool` | `boolean` |
|
|
98
|
+
| `buffer`, `optionalBuffer`, `fixed32`, `fixed64`, `raw` | `Buffer` |
|
|
99
|
+
| `date` | `Date` |
|
|
100
|
+
| `none` | `null` |
|
|
101
|
+
| `json` | `unknown` (a `json` field can hold any JSON value — object, array, or scalar) |
|
|
102
|
+
| `@ns/name` reference | the generated type name (e.g. `NsName`) |
|
|
103
|
+
|
|
104
|
+
And the modifiers:
|
|
105
|
+
|
|
106
|
+
- `array: true` → `T[]`
|
|
107
|
+
- a `record` type → `Record<string, V>` (records decode to a string-keyed object)
|
|
108
|
+
- an `enum` with `strings: true` → a string-literal union (`"a" | "b"`); otherwise a numeric-literal union
|
|
109
|
+
- an `alias` → `type X = <target>`
|
|
110
|
+
|
|
111
|
+
## Field type overrides (`tsType`)
|
|
112
|
+
|
|
113
|
+
A `json` field carries no shape information, so it defaults to `unknown`. To brand a field with a concrete TS type — like Drizzle's `.$type<T>()` — add a `tsType` to the field definition. It changes only the generated type, never the encoding:
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
ns.register({
|
|
117
|
+
name: 'doc',
|
|
118
|
+
fields: [
|
|
119
|
+
{ name: 'metrics', type: 'json', tsType: 'Metrics' }, // → metrics?: Metrics
|
|
120
|
+
{ name: 'status', type: 'string', tsType: '"on" | "off"' }, // → status?: "on" | "off" | null
|
|
121
|
+
{ name: 'ids', type: 'string', array: true, tsType: 'Id' } // → ids?: Id[] | null
|
|
122
|
+
]
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The override is applied as the element type, so `array: true` still wraps it (`Id[]`). You're responsible for ensuring the referenced type is in scope where the generated file is imported.
|
|
127
|
+
|
|
128
|
+
### `enum` — narrow a `string` field
|
|
129
|
+
|
|
130
|
+
For a field that stays `string` on the wire but only holds a fixed set of values (a status/state field you can't model as a real hyperschema enum because of append-only versioning), add an `enum` annotation. `tsType` gives you the compile-time union; `enum` makes [the validator](#validation) enforce membership at runtime:
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
{ name: 'state', type: 'string', enum: ['queued', 'running', 'done'], tsType: '"queued" | "running" | "done"' }
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`Validation.validate(schema, fqn, { state: 'paused' })` then fails with `state: must be one of "queued", "running", "done"`. For an `array` field the check applies element-wise. (A genuine hyperschema `enum` type is still preferable when you can use one — it also encodes as a 1-byte index and is rejected by compact-encoding itself.)
|
|
137
|
+
|
|
138
|
+
> Both `tsType` and `enum` are read from the live schema instance. Hyperschema does not persist unknown field keys to `schema.json`, so annotations only take effect when you generate types / validate in the same process that registers the schema (the usual `register` → `toDisk` build script). They are lost across a `Hyperschema.from('./dir')` reload.
|
|
139
|
+
|
|
140
|
+
## Optional fields and decode semantics
|
|
141
|
+
|
|
142
|
+
Hyperschema's non-`required` fields don't decode to `undefined` — they decode to the type's default. So the generated types reflect both sides:
|
|
143
|
+
|
|
144
|
+
- Every optional field is marked `?` (for the encode side).
|
|
145
|
+
- Optional fields whose default is `null` (objects, strings, buffers, arrays) are also unioned with `| null` (for the decode side).
|
|
146
|
+
- Optional scalar fields keep their plain type, since their default is a real value (`0`, `0n`, `false`), not `null`.
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
export interface Example {
|
|
150
|
+
id: number // required
|
|
151
|
+
score?: number // optional scalar → decodes to 0
|
|
152
|
+
blob?: Buffer | null // optional buffer → decodes to null
|
|
153
|
+
tags?: string[] | null // optional array → decodes to null
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
> Note: `bool` and bitwise uint fields are always optional, because hyperschema stores them in the struct's flags bitfield.
|
|
158
|
+
|
|
159
|
+
## Validation
|
|
160
|
+
|
|
161
|
+
`hyperschema-ts/validation` validates plain objects against a schema type _before_ you hand them to compact-encoding.
|
|
162
|
+
|
|
163
|
+
This matters because compact-encoding is mostly **silently lenient** — it only throws in a couple of cases and otherwise corrupts bad input without complaint:
|
|
164
|
+
|
|
165
|
+
| input | compact-encoding |
|
|
166
|
+
| -------------------- | ---------------------------------- |
|
|
167
|
+
| `ipv4("hello")` | silently encodes `143.0.0.0` |
|
|
168
|
+
| `uint8(9999)` | silently truncates to `15` |
|
|
169
|
+
| `hex("zz")` | silently encodes `00` |
|
|
170
|
+
| `uint(-5)` | **throws** `uint must be positive` |
|
|
171
|
+
| wrong-size `fixed32` | **throws** `Incorrect buffer size` |
|
|
172
|
+
|
|
173
|
+
The validator rejects everything compact-encoding would throw on _or_ silently corrupt (out-of-range numbers, malformed IPs, wrong buffer sizes, bad enum values, missing required fields, …), with a path for each failure.
|
|
174
|
+
|
|
175
|
+
```js
|
|
176
|
+
const Validation = require('hyperschema-ts/validation')
|
|
177
|
+
|
|
178
|
+
const { valid, errors } = Validation.validate(schema, '@example/request', {
|
|
179
|
+
id: 1,
|
|
180
|
+
host: 'hello' // not a valid IPv4
|
|
181
|
+
})
|
|
182
|
+
// valid === false
|
|
183
|
+
// errors === [{ path: '@example/request.host', value: 'hello', message: 'must be a valid IPv4 address' }]
|
|
184
|
+
|
|
185
|
+
// or throw an aggregated error:
|
|
186
|
+
Validation.assert(schema, '@example/request', obj)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### `Validation.validate(schema, fqn, value)`
|
|
190
|
+
|
|
191
|
+
Returns `{ valid, errors }`, where each error is `{ path, value, message }`. Never throws (except on an unknown `fqn`).
|
|
192
|
+
|
|
193
|
+
### `Validation.assert(schema, fqn, value)`
|
|
194
|
+
|
|
195
|
+
Throws an `Error` listing every failure if `value` is invalid; otherwise returns nothing.
|
|
196
|
+
|
|
197
|
+
### Typed validation (`createValidator`)
|
|
198
|
+
|
|
199
|
+
Every generated `types.d.ts` also exports a `SchemaTypes` registry mapping each `fqn` to its type. Pass it to `createValidator` and the validator becomes type-safe: `fqn` autocompletes (and typos fail to compile), and `is`/`assert` narrow `value` to the matching type.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import HyperschemaValidation from 'hyperschema-ts/validation'
|
|
203
|
+
import type { SchemaTypes } from './schema/types'
|
|
204
|
+
|
|
205
|
+
const v = HyperschemaValidation.createValidator<SchemaTypes>(schema)
|
|
206
|
+
|
|
207
|
+
if (v.is('@example/request', value)) {
|
|
208
|
+
value.id // value is ExampleRequest here
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
v.assert('@example/request', value) // throws, or narrows value to ExampleRequest
|
|
212
|
+
const { valid, errors } = v.validate('@example/request', value)
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
A `value is T` guard must return a boolean, so the three forms split by intent:
|
|
216
|
+
|
|
217
|
+
| method | returns | narrows? |
|
|
218
|
+
| ---------- | -------------------- | ------------------------- |
|
|
219
|
+
| `validate` | `{ valid, errors }` | no (use for error detail) |
|
|
220
|
+
| `is` | `value is T` | yes (boolean guard) |
|
|
221
|
+
| `assert` | `asserts value is T` | yes (throws on failure) |
|
|
222
|
+
|
|
223
|
+
> `createValidator` needs a live schema at runtime — typically `Hyperschema.from('./schema')` at startup. Note that a reload-from-disk schema loses field-level `tsType`/`enum` annotations (hyperschema doesn't persist them), so annotation-based `enum` membership only fires when validating against the same instance that registered the schema.
|
|
224
|
+
|
|
225
|
+
> Records are validated by value; their keys are always JS strings (compact-encoding records key on `Object.keys`). External and versioned types are treated as opaque (not validated structurally).
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
Apache-2.0
|
package/index.cjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const p = require('path')
|
|
3
|
+
|
|
4
|
+
const { emit, typeName } = require('./lib/codegen.js')
|
|
5
|
+
|
|
6
|
+
const CODE_FILE_NAME = 'types.d.ts'
|
|
7
|
+
|
|
8
|
+
class HyperschemaTS {
|
|
9
|
+
// Generate a TypeScript declaration string from a (resolved) Hyperschema instance.
|
|
10
|
+
static toCode(hyperschema, opts = {}) {
|
|
11
|
+
if (typeof hyperschema.linkAll === 'function') hyperschema.linkAll()
|
|
12
|
+
return emit(hyperschema, opts)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Mirror Hyperschema.toDisk(schema, dir?, opts?).
|
|
16
|
+
static toDisk(hyperschema, dir, opts) {
|
|
17
|
+
if (typeof dir === 'object' && dir) {
|
|
18
|
+
opts = dir
|
|
19
|
+
dir = null
|
|
20
|
+
}
|
|
21
|
+
opts = opts || {}
|
|
22
|
+
|
|
23
|
+
if (typeof hyperschema.linkAll === 'function') hyperschema.linkAll()
|
|
24
|
+
|
|
25
|
+
if (!dir) dir = hyperschema.dir
|
|
26
|
+
|
|
27
|
+
const codePath = opts.filename || p.join(p.resolve(dir), CODE_FILE_NAME)
|
|
28
|
+
fs.mkdirSync(p.dirname(codePath), { recursive: true })
|
|
29
|
+
fs.writeFileSync(codePath, emit(hyperschema, opts), { encoding: 'utf-8' })
|
|
30
|
+
|
|
31
|
+
return codePath
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
static typeName = typeName
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = HyperschemaTS
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface HyperschemaTSOptions {
|
|
2
|
+
/** Override the output path (defaults to `<dir>/types.d.ts`). */
|
|
3
|
+
filename?: string
|
|
4
|
+
/** Map of external fully-qualified type name -> TS expression to use for it. */
|
|
5
|
+
externals?: Record<string, string>
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Generates TypeScript type declarations from a Hyperschema instance.
|
|
10
|
+
* Pass the same `schema` you pass to `Hyperschema.toDisk`.
|
|
11
|
+
*/
|
|
12
|
+
export default class HyperschemaTS {
|
|
13
|
+
/** Generate the `.ts` source as a string. */
|
|
14
|
+
static toCode(hyperschema: any, opts?: HyperschemaTSOptions): string
|
|
15
|
+
|
|
16
|
+
/** Write the generated declarations to disk. Mirrors `Hyperschema.toDisk`. */
|
|
17
|
+
static toDisk(
|
|
18
|
+
hyperschema: any,
|
|
19
|
+
dir?: string | HyperschemaTSOptions,
|
|
20
|
+
opts?: HyperschemaTSOptions
|
|
21
|
+
): string
|
|
22
|
+
|
|
23
|
+
/** Convert a hyperschema fully-qualified name (e.g. `@example/my-struct`) to its TS type name. */
|
|
24
|
+
static typeName(fqn: string): string
|
|
25
|
+
}
|
package/index.mjs
ADDED
package/lib/codegen.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// Generates TypeScript type declarations from a resolved Hyperschema instance.
|
|
2
|
+
// Pure: reads the already-resolved `hyperschema.types` graph, returns a string.
|
|
3
|
+
|
|
4
|
+
// Maps every compact-encoding primitive (see hyperschema's lib/types.js) to a TS type.
|
|
5
|
+
const PRIMITIVE_GROUPS = {
|
|
6
|
+
number: [
|
|
7
|
+
'uint',
|
|
8
|
+
'uint1',
|
|
9
|
+
'uint2',
|
|
10
|
+
'uint3',
|
|
11
|
+
'uint4',
|
|
12
|
+
'uint5',
|
|
13
|
+
'uint6',
|
|
14
|
+
'uint7',
|
|
15
|
+
'uint8',
|
|
16
|
+
'uint16',
|
|
17
|
+
'uint24',
|
|
18
|
+
'uint32',
|
|
19
|
+
'uint40',
|
|
20
|
+
'uint48',
|
|
21
|
+
'uint56',
|
|
22
|
+
'uint64',
|
|
23
|
+
'int',
|
|
24
|
+
'int8',
|
|
25
|
+
'int16',
|
|
26
|
+
'int24',
|
|
27
|
+
'int32',
|
|
28
|
+
'int40',
|
|
29
|
+
'int48',
|
|
30
|
+
'int56',
|
|
31
|
+
'int64',
|
|
32
|
+
'float32',
|
|
33
|
+
'float64',
|
|
34
|
+
'port',
|
|
35
|
+
'lexint'
|
|
36
|
+
],
|
|
37
|
+
string: ['string', 'utf8', 'ascii', 'hex', 'ip', 'ipv4', 'ipv6'],
|
|
38
|
+
bigint: ['bigint', 'biguint64', 'bigint64'],
|
|
39
|
+
Buffer: ['fixed32', 'fixed64', 'buffer', 'optionalBuffer', 'raw'],
|
|
40
|
+
boolean: ['bool'],
|
|
41
|
+
Date: ['date'],
|
|
42
|
+
null: ['none'],
|
|
43
|
+
unknown: ['json']
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Primitives whose encoded value is an object rather than a scalar.
|
|
47
|
+
const PRIMITIVE_OBJECTS = {
|
|
48
|
+
ipAddress: '{ host: string; family?: number; port: number }',
|
|
49
|
+
ipv4Address: '{ host: string; family?: number; port: number }',
|
|
50
|
+
ipv6Address: '{ host: string; family?: number; port: number }'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const PRIMITIVES = new Map()
|
|
54
|
+
for (const [ts, names] of Object.entries(PRIMITIVE_GROUPS)) {
|
|
55
|
+
for (const name of names) PRIMITIVES.set(name, ts)
|
|
56
|
+
}
|
|
57
|
+
for (const [name, ts] of Object.entries(PRIMITIVE_OBJECTS)) PRIMITIVES.set(name, ts)
|
|
58
|
+
|
|
59
|
+
function pascal(segment) {
|
|
60
|
+
return segment
|
|
61
|
+
.split(/[-_\s]+/)
|
|
62
|
+
.filter(Boolean)
|
|
63
|
+
.map((w) => w[0].toUpperCase() + w.slice(1))
|
|
64
|
+
.join('')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function typeName(fqn) {
|
|
68
|
+
const stripped = fqn[0] === '@' ? fqn.slice(1) : fqn
|
|
69
|
+
return stripped.split('/').map(pascal).join('')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
73
|
+
function fieldKey(name) {
|
|
74
|
+
return IDENT.test(name) ? name : JSON.stringify(name)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Resolve a ResolvedType (+ array flag) to its TS expression.
|
|
78
|
+
function tsType(type, array, externals) {
|
|
79
|
+
if (array) return wrap(tsType(type, false, externals)) + '[]'
|
|
80
|
+
if (type.isPrimitive) return PRIMITIVES.get(type.name) || 'unknown'
|
|
81
|
+
if (type.isExternal) return externals[type.fqn] || 'unknown'
|
|
82
|
+
return typeName(type.fqn)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// A field's TS type, honouring a per-field `tsType` annotation (like Drizzle's
|
|
86
|
+
// `.$type<T>()`) which overrides the resolved element type without affecting encoding.
|
|
87
|
+
function fieldTsType(field, externals) {
|
|
88
|
+
const override = field.description && field.description.tsType
|
|
89
|
+
if (!override) return tsType(field.type, field.array, externals)
|
|
90
|
+
return field.array ? wrap(override) + '[]' : override
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function wrap(t) {
|
|
94
|
+
// parenthesise unions before appending `[]`
|
|
95
|
+
return /[|&]/.test(t) ? `(${t})` : t
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function structToInterface(type, externals) {
|
|
99
|
+
const lines = [`export interface ${typeName(type.fqn)} {`]
|
|
100
|
+
for (const field of type.fields) {
|
|
101
|
+
const ts = fieldTsType(field, externals)
|
|
102
|
+
const def = field.getDefaultValue() // undefined (useDefault:false) | null | scalar
|
|
103
|
+
if (field.required) {
|
|
104
|
+
lines.push(` ${fieldKey(field.name)}: ${ts}`)
|
|
105
|
+
} else {
|
|
106
|
+
const nullable = def === null // object/string/buffer/array optionals decode to null
|
|
107
|
+
lines.push(` ${fieldKey(field.name)}?: ${ts}${nullable ? ' | null' : ''}`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
lines.push('}')
|
|
111
|
+
return lines.join('\n')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function enumToType(type) {
|
|
115
|
+
if (!type.enum.length) return `export type ${typeName(type.fqn)} = never`
|
|
116
|
+
const members = type.strings
|
|
117
|
+
? type.enum.map((e) => JSON.stringify(e.key))
|
|
118
|
+
: type.enum.map((_, i) => String(type.offset + i))
|
|
119
|
+
return `export type ${typeName(type.fqn)} = ${members.join(' | ')}`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// fqn -> generated type name, for every type that produces a top-level declaration.
|
|
123
|
+
function registryToInterface(registry) {
|
|
124
|
+
const lines = ['export interface SchemaTypes {']
|
|
125
|
+
for (const [fqn, name] of registry) lines.push(` ${JSON.stringify(fqn)}: ${name}`)
|
|
126
|
+
lines.push('}')
|
|
127
|
+
return lines.join('\n')
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function emit(hyperschema, { externals = {}, registry = true } = {}) {
|
|
131
|
+
const decls = []
|
|
132
|
+
const entries = []
|
|
133
|
+
|
|
134
|
+
for (const type of hyperschema.types.values()) {
|
|
135
|
+
if (type.derived) continue
|
|
136
|
+
|
|
137
|
+
if (type.isStruct) {
|
|
138
|
+
decls.push(structToInterface(type, externals))
|
|
139
|
+
} else if (type.isEnum) {
|
|
140
|
+
decls.push(enumToType(type))
|
|
141
|
+
} else if (type.isAlias) {
|
|
142
|
+
decls.push(`export type ${typeName(type.fqn)} = ${tsType(type.type, false, externals)}`)
|
|
143
|
+
} else if (type.isArray) {
|
|
144
|
+
decls.push(
|
|
145
|
+
`export type ${typeName(type.fqn)} = ${wrap(tsType(type.type, false, externals))}[]`
|
|
146
|
+
)
|
|
147
|
+
} else if (type.isRecord) {
|
|
148
|
+
decls.push(
|
|
149
|
+
`export type ${typeName(type.fqn)} = Record<string, ${tsType(type.value, false, externals)}>`
|
|
150
|
+
)
|
|
151
|
+
} else {
|
|
152
|
+
// primitives / externals / versioned: nothing top-level
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
entries.push([type.fqn, typeName(type.fqn)])
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (registry) decls.push(registryToInterface(entries))
|
|
159
|
+
|
|
160
|
+
const header = [
|
|
161
|
+
'// This file is autogenerated by hyperschema-ts',
|
|
162
|
+
`// Schema version: ${hyperschema.version}`,
|
|
163
|
+
'// Do not edit manually.',
|
|
164
|
+
'',
|
|
165
|
+
''
|
|
166
|
+
].join('\n')
|
|
167
|
+
|
|
168
|
+
return header + decls.join('\n\n') + '\n'
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = { emit, typeName }
|
package/lib/validate.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// Runtime validation of plain objects against a Hyperschema type.
|
|
2
|
+
//
|
|
3
|
+
// compact-encoding is mostly *silently lenient* on bad input (it will encode
|
|
4
|
+
// ipv4('hello') to 143.0.0.0, truncate uint8(9999) to 15, etc.) and only throws
|
|
5
|
+
// in a couple of cases. This walks the same resolved-type graph the codegen uses
|
|
6
|
+
// and rejects everything compact-encoding would either throw on OR silently
|
|
7
|
+
// corrupt, with a field path for each failure.
|
|
8
|
+
|
|
9
|
+
const MAX_SAFE = Number.MAX_SAFE_INTEGER
|
|
10
|
+
|
|
11
|
+
function isInt(v) {
|
|
12
|
+
return typeof v === 'number' && Number.isInteger(v)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isBytes(v) {
|
|
16
|
+
return v instanceof Uint8Array
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function isPlainObject(v) {
|
|
20
|
+
return (
|
|
21
|
+
typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date) && !isBytes(v)
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function isIPv4(s) {
|
|
26
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s)
|
|
27
|
+
if (!m) return false
|
|
28
|
+
for (let i = 1; i <= 4; i++) {
|
|
29
|
+
if (Number(m[i]) > 255) return false
|
|
30
|
+
}
|
|
31
|
+
return true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isIPv6(s) {
|
|
35
|
+
if (typeof s !== 'string' || s.indexOf(':') === -1) return false
|
|
36
|
+
const parts = s.split('::')
|
|
37
|
+
if (parts.length > 2) return false
|
|
38
|
+
|
|
39
|
+
const group = /^[0-9a-fA-F]{1,4}$/
|
|
40
|
+
const head = parts[0] === '' ? [] : parts[0].split(':')
|
|
41
|
+
const tail = parts.length === 2 ? (parts[1] === '' ? [] : parts[1].split(':')) : null
|
|
42
|
+
|
|
43
|
+
for (const g of head) if (!group.test(g)) return false
|
|
44
|
+
if (tail) for (const g of tail) if (!group.test(g)) return false
|
|
45
|
+
|
|
46
|
+
// No compression: exactly 8 groups. With `::`: fewer groups, rest is zero-filled.
|
|
47
|
+
return tail === null ? head.length === 8 : head.length + tail.length <= 7
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// name -> { test(value) -> boolean, message }
|
|
51
|
+
const PRIMITIVES = new Map()
|
|
52
|
+
|
|
53
|
+
function set(name, test, message) {
|
|
54
|
+
PRIMITIVES.set(name, { test, message })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const UINT_BITS = {
|
|
58
|
+
uint1: 1,
|
|
59
|
+
uint2: 2,
|
|
60
|
+
uint3: 3,
|
|
61
|
+
uint4: 4,
|
|
62
|
+
uint5: 5,
|
|
63
|
+
uint6: 6,
|
|
64
|
+
uint7: 7,
|
|
65
|
+
uint8: 8,
|
|
66
|
+
uint16: 16,
|
|
67
|
+
uint24: 24,
|
|
68
|
+
uint32: 32,
|
|
69
|
+
uint40: 40,
|
|
70
|
+
uint48: 48,
|
|
71
|
+
uint56: 56,
|
|
72
|
+
uint64: 64
|
|
73
|
+
}
|
|
74
|
+
for (const [name, bits] of Object.entries(UINT_BITS)) {
|
|
75
|
+
const max = bits >= 53 ? MAX_SAFE : 2 ** bits - 1
|
|
76
|
+
set(name, (v) => isInt(v) && v >= 0 && v <= max, `must be an integer in [0, ${max}]`)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const INT_BITS = {
|
|
80
|
+
int8: 8,
|
|
81
|
+
int16: 16,
|
|
82
|
+
int24: 24,
|
|
83
|
+
int32: 32,
|
|
84
|
+
int40: 40,
|
|
85
|
+
int48: 48,
|
|
86
|
+
int56: 56,
|
|
87
|
+
int64: 64
|
|
88
|
+
}
|
|
89
|
+
for (const [name, bits] of Object.entries(INT_BITS)) {
|
|
90
|
+
const max = bits >= 54 ? MAX_SAFE : 2 ** (bits - 1) - 1
|
|
91
|
+
const min = bits >= 54 ? -MAX_SAFE : -(2 ** (bits - 1))
|
|
92
|
+
set(name, (v) => isInt(v) && v >= min && v <= max, `must be an integer in [${min}, ${max}]`)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
set('uint', (v) => isInt(v) && v >= 0 && v <= MAX_SAFE, 'must be a non-negative safe integer')
|
|
96
|
+
set('int', (v) => isInt(v) && v >= -MAX_SAFE && v <= MAX_SAFE, 'must be a safe integer')
|
|
97
|
+
set('lexint', (v) => isInt(v) && v >= 0 && v <= MAX_SAFE, 'must be a non-negative safe integer')
|
|
98
|
+
PRIMITIVES.set('port', PRIMITIVES.get('uint16'))
|
|
99
|
+
|
|
100
|
+
set('float32', (v) => typeof v === 'number' && Number.isFinite(v), 'must be a finite number')
|
|
101
|
+
set('float64', (v) => typeof v === 'number' && Number.isFinite(v), 'must be a finite number')
|
|
102
|
+
|
|
103
|
+
set(
|
|
104
|
+
'biguint64',
|
|
105
|
+
(v) => typeof v === 'bigint' && v >= 0n && v <= 0xffffffffffffffffn,
|
|
106
|
+
'must be a bigint in [0, 2^64 - 1]'
|
|
107
|
+
)
|
|
108
|
+
set(
|
|
109
|
+
'bigint64',
|
|
110
|
+
(v) => typeof v === 'bigint' && v >= -(2n ** 63n) && v <= 2n ** 63n - 1n,
|
|
111
|
+
'must be a bigint in [-2^63, 2^63 - 1]'
|
|
112
|
+
)
|
|
113
|
+
set('biguint', (v) => typeof v === 'bigint' && v >= 0n, 'must be a non-negative bigint')
|
|
114
|
+
set('bigint', (v) => typeof v === 'bigint', 'must be a bigint')
|
|
115
|
+
|
|
116
|
+
set('string', (v) => typeof v === 'string', 'must be a string')
|
|
117
|
+
PRIMITIVES.set('utf8', PRIMITIVES.get('string'))
|
|
118
|
+
// eslint-disable-next-line no-control-regex
|
|
119
|
+
set('ascii', (v) => typeof v === 'string' && /^[\x00-\x7f]*$/.test(v), 'must be an ASCII string')
|
|
120
|
+
set(
|
|
121
|
+
'hex',
|
|
122
|
+
(v) => typeof v === 'string' && v.length % 2 === 0 && /^[0-9a-fA-F]*$/.test(v),
|
|
123
|
+
'must be a hex string of even length'
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
set('buffer', isBytes, 'must be a Buffer or Uint8Array')
|
|
127
|
+
PRIMITIVES.set('optionalBuffer', PRIMITIVES.get('buffer'))
|
|
128
|
+
PRIMITIVES.set('raw', PRIMITIVES.get('buffer'))
|
|
129
|
+
set('fixed32', (v) => isBytes(v) && v.byteLength === 32, 'must be a 32-byte buffer')
|
|
130
|
+
set('fixed64', (v) => isBytes(v) && v.byteLength === 64, 'must be a 64-byte buffer')
|
|
131
|
+
|
|
132
|
+
set('bool', (v) => typeof v === 'boolean', 'must be a boolean')
|
|
133
|
+
set('date', (v) => v instanceof Date && Number.isFinite(v.getTime()), 'must be a valid Date')
|
|
134
|
+
set('none', () => true, '')
|
|
135
|
+
set('json', (v) => v !== undefined, 'must be JSON-serializable')
|
|
136
|
+
|
|
137
|
+
set('ipv4', (v) => typeof v === 'string' && isIPv4(v), 'must be a valid IPv4 address')
|
|
138
|
+
set('ipv6', (v) => typeof v === 'string' && isIPv6(v), 'must be a valid IPv6 address')
|
|
139
|
+
set('ip', (v) => typeof v === 'string' && (isIPv4(v) || isIPv6(v)), 'must be a valid IP address')
|
|
140
|
+
|
|
141
|
+
const ADDRESS_HOST = {
|
|
142
|
+
ipv4Address: isIPv4,
|
|
143
|
+
ipv6Address: isIPv6,
|
|
144
|
+
ipAddress: (s) => isIPv4(s) || isIPv6(s)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function err(errors, path, value, message) {
|
|
148
|
+
errors.push({ path, value, message })
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isPort(v) {
|
|
152
|
+
return isInt(v) && v >= 0 && v <= 65535
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function checkAddress(name, value, path, errors) {
|
|
156
|
+
if (!isPlainObject(value)) {
|
|
157
|
+
err(errors, path, value, 'must be an { host, port } object')
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
if (typeof value.host !== 'string' || !ADDRESS_HOST[name](value.host)) {
|
|
161
|
+
err(errors, path + '.host', value.host, 'must be a valid IP address')
|
|
162
|
+
}
|
|
163
|
+
if (!isPort(value.port)) {
|
|
164
|
+
err(errors, path + '.port', value.port, 'must be a port in [0, 65535]')
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Field-level `enum: [...]` annotation: domain membership for a field whose wire
|
|
169
|
+
// type stays as-is (typically `string`). Mirrors the type-level enum check.
|
|
170
|
+
function checkMembership(allowed, value, array, path, errors) {
|
|
171
|
+
const message = `must be one of ${allowed.map((a) => JSON.stringify(a)).join(', ')}`
|
|
172
|
+
const one = (val, p) => {
|
|
173
|
+
if (!allowed.includes(val)) err(errors, p, val, message)
|
|
174
|
+
}
|
|
175
|
+
if (array) {
|
|
176
|
+
if (Array.isArray(value)) value.forEach((el, i) => one(el, `${path}[${i}]`))
|
|
177
|
+
} else {
|
|
178
|
+
one(value, path)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function checkValue(type, value, array, path, errors) {
|
|
183
|
+
if (array) {
|
|
184
|
+
if (!Array.isArray(value)) {
|
|
185
|
+
err(errors, path, value, 'must be an array')
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
for (let i = 0; i < value.length; i++) {
|
|
189
|
+
checkValue(type, value[i], false, `${path}[${i}]`, errors)
|
|
190
|
+
}
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (type.isPrimitive) {
|
|
195
|
+
if (ADDRESS_HOST[type.name]) {
|
|
196
|
+
checkAddress(type.name, value, path, errors)
|
|
197
|
+
return
|
|
198
|
+
}
|
|
199
|
+
const p = PRIMITIVES.get(type.name)
|
|
200
|
+
if (p && !p.test(value)) err(errors, path, value, p.message)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (type.isAlias) {
|
|
205
|
+
checkValue(type.type, value, false, path, errors)
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (type.isEnum) {
|
|
210
|
+
const keys = type.enum.map((e) => e.key)
|
|
211
|
+
const ok = type.strings
|
|
212
|
+
? keys.includes(value)
|
|
213
|
+
: isInt(value) && value >= type.offset && value < type.offset + keys.length
|
|
214
|
+
if (!ok) {
|
|
215
|
+
const allowed = type.strings
|
|
216
|
+
? keys.map((k) => JSON.stringify(k)).join(', ')
|
|
217
|
+
: `[${type.offset}, ${type.offset + keys.length - 1}]`
|
|
218
|
+
err(errors, path, value, `must be one of ${allowed}`)
|
|
219
|
+
}
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (type.isArray) {
|
|
224
|
+
checkValue(type.type, value, true, path, errors)
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (type.isRecord) {
|
|
229
|
+
if (!isPlainObject(value)) {
|
|
230
|
+
err(errors, path, value, 'must be an object')
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
for (const key of Object.keys(value)) {
|
|
234
|
+
checkValue(type.value, value[key], false, `${path}.${key}`, errors)
|
|
235
|
+
}
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (type.isStruct) {
|
|
240
|
+
if (!isPlainObject(value)) {
|
|
241
|
+
err(errors, path, value, 'must be an object')
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
for (const field of type.fields) {
|
|
245
|
+
const v = value[field.name]
|
|
246
|
+
const present = v !== undefined && v !== null
|
|
247
|
+
if (!present) {
|
|
248
|
+
if (field.required) err(errors, `${path}.${field.name}`, v, 'is required')
|
|
249
|
+
continue
|
|
250
|
+
}
|
|
251
|
+
const fieldPath = `${path}.${field.name}`
|
|
252
|
+
checkValue(field.type, v, field.array, fieldPath, errors)
|
|
253
|
+
if (field.description && field.description.enum) {
|
|
254
|
+
checkMembership(field.description.enum, v, field.array, fieldPath, errors)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// external / versioned: cannot validate structurally, treat as opaque
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function validate(schema, fqn, value) {
|
|
264
|
+
if (typeof schema.linkAll === 'function') schema.linkAll()
|
|
265
|
+
|
|
266
|
+
const type = schema.resolve(fqn)
|
|
267
|
+
if (!type) throw new Error(`Unknown type: ${fqn}`)
|
|
268
|
+
|
|
269
|
+
const errors = []
|
|
270
|
+
checkValue(type, value, false, fqn, errors)
|
|
271
|
+
return { valid: errors.length === 0, errors }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
module.exports = { validate, PRIMITIVES }
|
package/package.json
CHANGED
|
@@ -1 +1,67 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "hyperschema-ts",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Generate TypeScript types from a Hyperschema",
|
|
5
|
+
"exports": {
|
|
6
|
+
"./package": "./package.json",
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"import": "./index.mjs",
|
|
10
|
+
"default": "./index.cjs"
|
|
11
|
+
},
|
|
12
|
+
"./validation": {
|
|
13
|
+
"types": "./validation.d.ts",
|
|
14
|
+
"import": "./validation.mjs",
|
|
15
|
+
"default": "./validation.cjs"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"imports": {
|
|
19
|
+
"fs": {
|
|
20
|
+
"bare": "bare-fs",
|
|
21
|
+
"default": "fs"
|
|
22
|
+
},
|
|
23
|
+
"path": {
|
|
24
|
+
"bare": "bare-path",
|
|
25
|
+
"default": "path"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"package.json",
|
|
30
|
+
"index.mjs",
|
|
31
|
+
"index.cjs",
|
|
32
|
+
"index.d.ts",
|
|
33
|
+
"validation.mjs",
|
|
34
|
+
"validation.cjs",
|
|
35
|
+
"validation.d.ts",
|
|
36
|
+
"lib"
|
|
37
|
+
],
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"brittle": "^4.0.2",
|
|
40
|
+
"hyperschema": "^1.21.0",
|
|
41
|
+
"lunte": "^1.2.0",
|
|
42
|
+
"prettier": "^3.6.2",
|
|
43
|
+
"prettier-config-holepunch": "^2.0.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"hyperschema": "^1.21.0"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"format": "prettier . --write",
|
|
50
|
+
"test": "brittle-bare test/index.js && brittle-node test/index.js",
|
|
51
|
+
"lint": "prettier . --check && lunte"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "https://github.com/holepunchto/hyperschema-ts.git"
|
|
56
|
+
},
|
|
57
|
+
"author": "Holepunch Inc",
|
|
58
|
+
"license": "Apache-2.0",
|
|
59
|
+
"bugs": {
|
|
60
|
+
"url": "https://github.com/holepunchto/hyperschema-ts/issues"
|
|
61
|
+
},
|
|
62
|
+
"homepage": "https://github.com/holepunchto/hyperschema-ts",
|
|
63
|
+
"dependencies": {
|
|
64
|
+
"bare-fs": "^4.7.2",
|
|
65
|
+
"bare-path": "^3.0.1"
|
|
66
|
+
}
|
|
67
|
+
}
|
package/validation.cjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const { validate } = require('./lib/validate.js')
|
|
2
|
+
|
|
3
|
+
class HyperschemaValidation {
|
|
4
|
+
// Validate `value` against the type `fqn` registered on a Hyperschema instance.
|
|
5
|
+
// Returns { valid: boolean, errors: Array<{ path, value, message }> }.
|
|
6
|
+
static validate(schema, fqn, value) {
|
|
7
|
+
return validate(schema, fqn, value)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Boolean type guard: narrows `value` to the matching type when used through
|
|
11
|
+
// a typed validator (see createValidator).
|
|
12
|
+
static is(schema, fqn, value) {
|
|
13
|
+
return validate(schema, fqn, value).valid
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Validate and throw an aggregated error if `value` is invalid.
|
|
17
|
+
static assert(schema, fqn, value) {
|
|
18
|
+
const { valid, errors } = validate(schema, fqn, value)
|
|
19
|
+
if (!valid) {
|
|
20
|
+
const summary = errors.map((e) => ` ${e.path}: ${e.message}`).join('\n')
|
|
21
|
+
throw new Error(`Invalid ${fqn}:\n${summary}`)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Bind a schema and return a validator whose `fqn` argument is constrained to
|
|
26
|
+
// the generated `SchemaTypes` keys, and whose `is`/`assert` narrow to the
|
|
27
|
+
// matching generated type. Pass the generated `SchemaTypes` as the type param:
|
|
28
|
+
// const v = HyperschemaValidation.createValidator<SchemaTypes>(schema)
|
|
29
|
+
static createValidator(schema) {
|
|
30
|
+
return {
|
|
31
|
+
validate: (fqn, value) => validate(schema, fqn, value),
|
|
32
|
+
is: (fqn, value) => validate(schema, fqn, value).valid,
|
|
33
|
+
assert: (fqn, value) => HyperschemaValidation.assert(schema, fqn, value)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = HyperschemaValidation
|
package/validation.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export interface ValidationError {
|
|
2
|
+
/** Dotted path to the offending value, e.g. `@example/request.host`. */
|
|
3
|
+
path: string
|
|
4
|
+
/** The value that failed validation. */
|
|
5
|
+
value: unknown
|
|
6
|
+
/** Human-readable reason. */
|
|
7
|
+
message: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ValidationResult {
|
|
11
|
+
valid: boolean
|
|
12
|
+
errors: ValidationError[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A schema-bound validator whose `fqn` is constrained to the generated
|
|
17
|
+
* `SchemaTypes` keys, and whose `is`/`assert` narrow `value` to the matching
|
|
18
|
+
* generated type. `M` is the generated `SchemaTypes` interface.
|
|
19
|
+
*/
|
|
20
|
+
export interface TypedValidator<M> {
|
|
21
|
+
/** Rich result; `fqn` is constrained to known types but `value` is not narrowed. */
|
|
22
|
+
validate<K extends keyof M>(fqn: K, value: unknown): ValidationResult
|
|
23
|
+
/** Boolean type guard that narrows `value` to `M[K]`. */
|
|
24
|
+
is<K extends keyof M>(fqn: K, value: unknown): value is M[K]
|
|
25
|
+
/** Assertion that narrows `value` to `M[K]` or throws. */
|
|
26
|
+
assert<K extends keyof M>(fqn: K, value: unknown): asserts value is M[K]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Validates plain objects against a Hyperschema type before they are passed to
|
|
31
|
+
* compact-encoding. Rejects everything compact-encoding would throw on or
|
|
32
|
+
* silently corrupt (out-of-range numbers, malformed IPs, wrong buffer sizes, …).
|
|
33
|
+
*/
|
|
34
|
+
export default class HyperschemaValidation {
|
|
35
|
+
/** Validate `value` against the type `fqn` registered on `schema`. */
|
|
36
|
+
static validate(schema: any, fqn: string, value: unknown): ValidationResult
|
|
37
|
+
|
|
38
|
+
/** Boolean check that `value` is a valid `fqn`. */
|
|
39
|
+
static is(schema: any, fqn: string, value: unknown): boolean
|
|
40
|
+
|
|
41
|
+
/** Validate and throw an aggregated error if `value` is invalid. */
|
|
42
|
+
static assert(schema: any, fqn: string, value: unknown): void
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Bind a schema and return a validator typed against the generated `SchemaTypes`.
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* import HyperschemaValidation from 'hyperschema-ts/validation'
|
|
49
|
+
* import type { SchemaTypes } from './schema/types'
|
|
50
|
+
*
|
|
51
|
+
* const v = HyperschemaValidation.createValidator<SchemaTypes>(schema)
|
|
52
|
+
* if (v.is('@example/request', value)) value.id // value: ExampleRequest
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
static createValidator<M = Record<string, unknown>>(schema: any): TypedValidator<M>
|
|
56
|
+
}
|
package/validation.mjs
ADDED