json-2-joi 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,153 @@
1
+ ### 9.0.1
2
+
3
+ * #112 Use joi.link to only resolve strictly recursive self-references
4
+
5
+ ### 9.0.0
6
+
7
+ * #100 Allow extension constructors
8
+ * #101 Keep string enum type
9
+ * #104 Allow allOf, anyOf, oneOf to be combined with base schema
10
+ * #107 Cycles in schema refs (fixed #106)
11
+ * #108 Handle `not` properly
12
+ * #109 Defaults options
13
+
14
+ ### 8.0.0
15
+
16
+ * [BREAKING] Switched from @hapi/joi to joi (#94)
17
+ * Added refineSchema function (#92)
18
+
19
+ ### 7.0.0
20
+
21
+ * [BREAKING] Updated to Joi@17
22
+ * [BREAKING] Custom types moved to being defined under `extensions`
23
+ * [BREAKING] Extensions definitions to follow Joi@17
24
+
25
+ ### 6.0.2
26
+
27
+ * Correct usage of joi `validate` function. joiSchema.validate(obj) instead of Joi.validate(obj, joiSchema).
28
+
29
+ ### 6.0.1
30
+
31
+ * #83 differentiate between undefined and falsy
32
+ * #73 updated fix
33
+
34
+ ### 6.0.0
35
+
36
+ * Do not set empty string as valid for all string types (#73)
37
+ * Updated joi and hoek to latest, drop Node 6 support (#76)
38
+
39
+ ### v5.0.1
40
+
41
+ * #69
42
+
43
+ ### v5.0.1
44
+
45
+ * #66
46
+
47
+ ### v5.0.0
48
+
49
+ * [BREAKING] Addresses #63 : date format to follow RFC3339 as per JSON-Schema.
50
+
51
+ ### v4.1.1
52
+
53
+ * Fixes `oneOf` requiring (#61).
54
+
55
+ ### v4.1.0
56
+
57
+ * Added support for string formats `uuid` (v4) and `guid`.
58
+
59
+ ### v4.0.0
60
+
61
+ * [BREAKING] export interface changed. Call `Enjoi.schema` instead of `Enjoi`.
62
+ * [BREAKING] `joi` is a peer.
63
+ * Added `extensions` support.
64
+ * `types` can also contain function values to do complex resolving of custom types.
65
+ * Added support for `Enjoi.defaults` which returns a new Enjoi with default options.
66
+
67
+ ### v3.2.5
68
+
69
+ * Fixed allOf support (#53)
70
+
71
+ ### v3.2.4
72
+
73
+ * Support for allOf
74
+ * Bug fixes
75
+
76
+ ### v3.2.3
77
+
78
+ * Security fix to resolve https://nodesecurity.io/advisories/566
79
+
80
+ ### v3.2.2
81
+
82
+ * Documentation fixes.
83
+
84
+ ### v3.2.1
85
+
86
+ * Support array:additionalItems false setting.
87
+
88
+ ### v3.2.0
89
+
90
+ * Added `strictMode` support and resolves #34.
91
+
92
+ ### v3.1.0
93
+
94
+ * Added a refineType function option.
95
+
96
+ ### v3.0.0
97
+
98
+ * [BREAKING] supports Joi 13.x (required Node 6+)
99
+ * Fixed additional properties https://github.com/tlivings/enjoi/pull/31
100
+ * Adds support for ordered and items https://github.com/tlivings/enjoi/pull/38
101
+
102
+ ### v2.2.4
103
+
104
+ * Fixes mutating `options` to add `stripUnknown`.
105
+
106
+ ### v2.2.3
107
+
108
+ * Fix #25 by supporting array for type (e.g. ['string', 'null']).
109
+ * Additional formats: hostname, uri, ipv4, ipv6.
110
+
111
+ ### v2.2.2
112
+
113
+ * Added @jsdevel's additionalProperties (#14) fixes (thanks!)
114
+
115
+ ### v2.2.1
116
+
117
+ * Add default value (#30).
118
+
119
+ ### v2.2.0
120
+
121
+ * Added support for directly passing a `string` instead of a schema to indicate type.
122
+
123
+ ### v2.1.0
124
+
125
+ * added support for mapping title (to label in joi).
126
+ * added support for mapping description.
127
+ * fixed engine version.
128
+
129
+ ### v2.0.0
130
+
131
+ * updated `joi` to ^9.
132
+ * requires node 4 minimum.
133
+
134
+ ### v1.0.4
135
+
136
+ * when undefined `minLength` should default to 0.
137
+
138
+ ### v1.0.3
139
+
140
+ * Validate when `additionalProperties` is boolean.
141
+
142
+ ### v1.0.2
143
+
144
+ * Support for `oneOf`.
145
+
146
+ ### v1.0.1
147
+
148
+ * Support for `format` in string types.
149
+
150
+ ### v1.0.0
151
+
152
+ * [BREAKING] `subSchemas` is now passed as a property in `options`.
153
+ * Support for custom types using `options.types`.
package/LICENSE.txt ADDED
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright (c) Trevor Livingston.
191
+ All rights reserved.
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,279 @@
1
+
2
+
3
+ # json-2-joi
4
+
5
+ Converts a JSON schema to a Joi schema for object validation.
6
+
7
+ ## Change based on the forked version (Json2Joi):
8
+
9
+ - Provided `refineDescription(schema)`, `allowNull` options
10
+ - Change cycle reference resovling without self-generating id and rely on $id if defined in JSON schema
11
+ - Support `const` keyword in JSON schema
12
+ - Support `example` setting for Joi based on JSON schema's `examples`, `default` or `enum`
13
+ - Support `contains` keyword in JSON schema using Joi's `has` method
14
+ - Support `$anchor` keyword in JSON schema
15
+ - **Big Change** on `$ref` and `subSchemas`. Please refer to [test/test-references.js](test/test-references.js) for detail usage. Currently, four format of `$ref` are supported:
16
+ * id
17
+ * [baseUri]#anchor
18
+ * [baseUri]#/$defs/shared
19
+ * [baseUri]#/$defs/shared/properties/level1
20
+
21
+ **subSchemas** will be modified for two reason:
22
+ * If any subSchema does not have `$id` field, it will be added using the corresponding key in `subSchemas` object.
23
+ * New key-value pair will be added into it if the **schema** or any its subschema being parsed has `$id` field. Root schema will be added into it as well (if missing $id field, empty string is used as key).
24
+
25
+ ## Usage
26
+
27
+ ### Schema Support
28
+
29
+ `json2Joi` does not support all of json-schema.
30
+
31
+ Here is a list of some known missing keyword support still being worked on:
32
+
33
+ - `object:patternProperties` - unsupported due to Joi limitations.
34
+
35
+ Please file issues for other unsupported features.
36
+
37
+ ### API
38
+
39
+ - `json2Joi.schema(schema [, options])`
40
+ - `schema` - a JSON schema or a string type representation (such as `'integer'`).
41
+ - `options` - an (optional) object of additional options such as `subSchemas` and custom `types`.
42
+ - `json2Joi.resolver(options)` - Creates a schema resolver based on `options`.
43
+
44
+ ### Options
45
+
46
+ - `subSchemas` - an (optional) object with keys representing schema ids, and values representing schemas.
47
+ - `refineDescription(schema)` - an (optional) function to call to apply to the JSON schema so that it's possible to return customized description.
48
+ - `refineType(type, format)` - an (optional) function to call to apply to type based on the type and format of the JSON schema.
49
+ - `refineSchema(joiSchema, jsonSchema)` - an (optional) function to call to apply to adjust Joi schema base on the original JSON schema. Primary use case is handling `nullable` flag in OpenAPI 3.0
50
+ - `extensions` - an array of extensions to pass [joi.extend](https://github.com/hapijs/joi/blob/master/API.md#extendextension).
51
+ - `allowNull` - Allows null value when the field is NOT required with a default value of `false`.
52
+ - `strictMode` - make schemas `strict(value)` with a default value of `false`.
53
+
54
+ Example:
55
+
56
+ ```javascript
57
+ const Joi = require('joi');
58
+ const Json2Joi = require('json-2-joi');
59
+
60
+ const schema = Json2Joi.schema({
61
+ type: 'object',
62
+ properties: {
63
+ firstName: {
64
+ description: 'First name.',
65
+ type: 'string'
66
+ },
67
+ lastName: {
68
+ description: 'Last name.',
69
+ type: 'string'
70
+ },
71
+ age: {
72
+ description: 'Age in years',
73
+ type: 'integer',
74
+ minimum: 1
75
+ }
76
+ },
77
+ 'required': ['firstName', 'lastName']
78
+ });
79
+
80
+ const { error, value } = schema.validate({firstName: 'John', lastName: 'Doe', age: 45});
81
+ ```
82
+
83
+ ### Sub Schemas
84
+
85
+ Sub-schemas can be provided through the `subSchemas` option for `$ref` values to lookup against.
86
+
87
+ Example:
88
+
89
+ ```javascript
90
+ const schema = Json2Joi.schema({
91
+ $id: 'top',
92
+ type: 'object',
93
+ properties: {
94
+ product: {
95
+ $ref: 'prod'
96
+ },
97
+ suggestions: {
98
+ type: 'array',
99
+ items: {
100
+ type: 'object',
101
+ properties: {
102
+ product: {
103
+ $ref: 'product'
104
+ },
105
+ weight: {
106
+ $ref: 'measurement'
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+ }, {
113
+ subSchemas: {
114
+ measurement: {
115
+ type: 'object',
116
+ properties: {
117
+ quantity: {
118
+ $anchor: 'subNumber',
119
+ type: 'number'
120
+ },
121
+ unit: {
122
+ type: 'string'
123
+ }
124
+ }
125
+ },
126
+ product: {
127
+ $id: 'prod',
128
+ type: 'object',
129
+ properties: {
130
+ isUsed: {
131
+ $anchor: 'subBoolean',
132
+ type: 'boolean'
133
+ },
134
+ isDangerous: {
135
+ $ref: '#subBoolean'
136
+ },
137
+ width: {
138
+ $ref: 'measurement'
139
+ },
140
+ length: {
141
+ $ref: '#/properties/width'
142
+ },
143
+ price: {
144
+ $ref: 'measurement#subNumber'
145
+ }
146
+ }
147
+ }
148
+ }
149
+ });
150
+ ```
151
+
152
+ ### Reuse JOI Schema Resolver
153
+
154
+ Sometimes, we might have a base set of `subSchemas` which is used for building a large number of JSON schema and so we do not want to parse these common `subSchemas` again and again. We can first construct a JOI Schema Resolver first and then convert other JSON one by one.
155
+
156
+ ```javascript
157
+
158
+ const json2Joi = Json2Joi.resolver({
159
+ subSchemas: {
160
+ measurement: {
161
+ type: 'object',
162
+ properties: {
163
+ quantity: {
164
+ $anchor: 'subNumber',
165
+ type: 'number'
166
+ },
167
+ unit: {
168
+ type: 'string'
169
+ }
170
+ }
171
+ }
172
+ }
173
+ });
174
+
175
+ const weightSchema = json2Joi.convert({
176
+ type: 'object',
177
+ properties: {
178
+ weight: {
179
+ $ref: 'measurement'
180
+ }
181
+ }
182
+ });
183
+
184
+ const lengthSchema = json2Joi.convert({
185
+ type: 'object',
186
+ properties: {
187
+ length: {
188
+ $ref: 'measurement'
189
+ }
190
+ }
191
+ });
192
+ ```
193
+
194
+ ### Custom Types
195
+
196
+ Custom types can be provided through the `extensions` option.
197
+
198
+ ```javascript
199
+ const schema = Json2Joi.schema({
200
+ type: 'thing'
201
+ }, {
202
+ extensions: [{
203
+ type: 'thing',
204
+ base: Joi.any()
205
+ }]
206
+ });
207
+ ```
208
+
209
+ Also with functions.
210
+
211
+ ```javascript
212
+ const schema = Json2Joi.schema({
213
+ type: 'thing'
214
+ }, {
215
+ extensions: [{
216
+ type: 'thing',
217
+ validate(value, helpers) {
218
+ if (value !== 'foobar') {
219
+ return { value, errors: helpers.error('thing.foobar') };
220
+ }
221
+ },
222
+ messages: {
223
+ 'thing.foobar': '{#label} must be \'foobar\''
224
+ }
225
+ }]
226
+ });
227
+ ```
228
+
229
+ ### Refine Type
230
+
231
+ You can use the refine type function to help refine types based on `type` and `format`. This will allow transforming a type for lookup.
232
+
233
+ ```javascript
234
+ const schema = Json2Joi.schema({
235
+ type: 'string',
236
+ format: 'email'
237
+ }, {
238
+ extensions: [{
239
+ type: 'email',
240
+ base: Joi.string().email()
241
+ }],
242
+ refineType(type, format) {
243
+ if (type === 'string' && format === 'email') {
244
+ return 'email';
245
+ }
246
+ }
247
+ });
248
+ ```
249
+
250
+ This can be used in conjunction with function based `extensions` for additional logic:
251
+
252
+ ```javascript
253
+ const schemaDesc = {
254
+ type: 'string',
255
+ format: 'email',
256
+ 'x-test': true
257
+ }
258
+ const schema = Json2Joi.schema(schemaDesc, {
259
+ extensions: [{
260
+ type: 'email',
261
+ validate(value, helpers) {
262
+ const validator = schemaDesc['x-test'] ? Joi.string().email().equal('test@example.com') : Joi.string().email();
263
+ const validation = validator.validate(value);
264
+ if (validation.error) {
265
+ return { value, errors: validation.error };
266
+ }
267
+ }
268
+ }],
269
+ refineType(type, format) {
270
+ if (type === 'string' && format === 'email') {
271
+ return 'email';
272
+ }
273
+ }
274
+ });
275
+ ```
276
+
277
+ ### Extensions
278
+
279
+ Refer to Joi documentation on extensions: https://hapi.dev/module/joi/api/?v=17#extensions
package/index.js ADDED
@@ -0,0 +1,14 @@
1
+ const SchemaResolver = require('./lib/resolver');
2
+
3
+ function resolver(options = {}) {
4
+ return new SchemaResolver(options);
5
+ }
6
+
7
+ function schema(schema, options = { }) {
8
+ const joiResolver = resolver(options);
9
+ const joiSchema = joiResolver.convert(schema);
10
+ return joiSchema;
11
+ }
12
+
13
+ exports.resolver = resolver;
14
+ exports.schema = schema;
@@ -0,0 +1,582 @@
1
+ /* global Map */
2
+ const Joi = require('joi');
3
+ const Hoek = require('@hapi/hoek');
4
+ const Bourne = require('@hapi/bourne');
5
+ const debugCreator = require('debug');
6
+
7
+ const debug = debugCreator('enjoi');
8
+
9
+ debugCreator.formatters.f = function (f) {
10
+ return f();
11
+ }
12
+
13
+ const schemaSchema = Joi.alternatives(Joi.object().unknown(true), Joi.string()).required();
14
+ const extensionSchema = Joi.alternatives().try(Joi.object().unknown(true), Joi.function())
15
+
16
+ const optionsSchema = Joi.object({
17
+ subSchemas: Joi.object().unknown(true).default({}),
18
+ extensions: Joi.array().items(extensionSchema).default([]),
19
+ refineType: Joi.func().allow(null),
20
+ refineSchema: Joi.func().allow(null),
21
+ refineDescription: Joi.func().allow(null),
22
+ allowNull: Joi.boolean().default(false),
23
+ strictMode: Joi.boolean().default(false),
24
+ useDefaults: Joi.boolean().default(false)
25
+ });
26
+
27
+ function isNumber(value) {
28
+ return typeof value === 'number';
29
+ }
30
+
31
+ function isObject(value) {
32
+ return value !== null && typeof value === 'object';
33
+ }
34
+
35
+ function normalizedId(id) {
36
+ return id.replace(/[^a-zA-Z0-9]/g, '_');
37
+ }
38
+
39
+ const mapToObj = m => {
40
+ return Array.from(m).reduce((obj, [key, value]) => {
41
+ obj[key] = Joi.isSchema(value) ? value.describe() : value;
42
+ return obj;
43
+ }, {});
44
+ };
45
+
46
+ class SchemaResolver {
47
+ constructor(options) {
48
+ const validatedResult = optionsSchema.validate(options);
49
+
50
+ Hoek.assert(!validatedResult.error, validatedResult.error);
51
+
52
+ const { subSchemas = {}, refineType, refineSchema, strictMode, useDefaults, extensions = [], allowNull = false, refineDescription } = validatedResult.value;
53
+
54
+ this.subSchemas = subSchemas;
55
+ this.refineType = refineType;
56
+ this.refineDescription = refineDescription;
57
+ this.refineSchema = refineSchema;
58
+ this.strictMode = strictMode;
59
+ this.useDefaults = useDefaults;
60
+ this.allowNull = allowNull;
61
+ this.joiSharedSchemas = new Map();
62
+
63
+ this.joi = Joi.extend(
64
+ {
65
+ type: 'object',
66
+ base: Joi.object(),
67
+ coerce: {
68
+ from: 'string',
69
+ method(value) {
70
+ if (typeof value !== 'string' || (value[0] !== '{' && !/^\s*\{/.test(value))) {
71
+ return;
72
+ }
73
+
74
+ try {
75
+ return { value: Bourne.parse(value) };
76
+ } catch (ignoreErr) { } // eslint-disable-line no-empty
77
+ }
78
+ }
79
+ },
80
+ {
81
+ type: 'array',
82
+ base: Joi.array(),
83
+ coerce: {
84
+ from: 'string',
85
+ method(value) {
86
+ if (typeof value !== 'string' || (value[0] !== '[' && !/^\s*\[/.test(value))) {
87
+ return;
88
+ }
89
+ try {
90
+ return { value: Bourne.parse(value) };
91
+ } catch (ignoreErr) { } // eslint-disable-line no-empty
92
+ }
93
+ }
94
+ },
95
+ ...extensions
96
+ );
97
+
98
+ for (let sharedSchemaId in this.subSchemas) {
99
+ const sharedSchema = this.subSchemas[sharedSchemaId];
100
+ if (typeof sharedSchema === 'object' && !sharedSchema.$id) {
101
+ // shorthand schema type does not need to set $id
102
+ sharedSchema.$id = sharedSchemaId;
103
+ }
104
+ this.joiSharedSchemas.set(sharedSchemaId, this.resolve(sharedSchema));
105
+ }
106
+
107
+ const itr = this.joiSharedSchemas.keys();
108
+ this.initialSharedSchemaIds = [];
109
+ for (const id of itr) {
110
+ this.initialSharedSchemaIds.push(id);
111
+ }
112
+ }
113
+
114
+ resolveShareSchemas(schema, baseUri = '', sharedProperties = '$defs') {
115
+ const localShared = schema[sharedProperties]
116
+ if (localShared) {
117
+ for (let sharedSchemaId in localShared) {
118
+ this.joiSharedSchemas.set(
119
+ `${baseUri}#/${sharedProperties}/${sharedSchemaId}`,
120
+ this.resolve(localShared[sharedSchemaId], baseUri)
121
+ );
122
+ }
123
+ }
124
+ }
125
+
126
+ convert(schema) {
127
+ const validateSchema = schemaSchema.validate(schema);
128
+
129
+ Hoek.assert(!validateSchema.error, validateSchema.error);
130
+
131
+ const schemaId = schema.$id || '';
132
+ this.subSchemas[schemaId] = schema;
133
+ const joiSchema = this.resolve(schema);
134
+
135
+ // Cleanup all shared schema registered other than the initial shared ones
136
+ delete this.subSchemas[schemaId];
137
+ const itr = this.joiSharedSchemas.keys();
138
+ for (const id of itr) {
139
+ if (!this.initialSharedSchemaIds.includes(id)) {
140
+ delete this.subSchemas[id];
141
+ this.joiSharedSchemas.delete(id);
142
+ }
143
+ }
144
+ return joiSchema;
145
+ }
146
+
147
+ resolve(schema, baseUri = (schema.$id || '')) {
148
+ if (this.joi.isSchema(schema)) {
149
+ return schema;
150
+ }
151
+
152
+ const schemaId = schema.$id;
153
+ let resolvedSchema;
154
+
155
+ if (schemaId) {
156
+ baseUri = schemaId;
157
+ if (!this.subSchemas[schemaId]) {
158
+ this.subSchemas[schemaId] = schema;
159
+ }
160
+ }
161
+
162
+ this.resolveShareSchemas(schema, baseUri, '$defs');
163
+ this.resolveShareSchemas(schema, baseUri, 'definitions');
164
+
165
+ if (typeof schema === 'string') {
166
+ // If schema is itself a string, interpret it as a type
167
+ resolvedSchema = this.resolveType({ type: schema });
168
+ } else if (schema.$ref) {
169
+ if (schema.$ref.trim() === '#') {
170
+ return baseUri ? this.joi.link(`#${normalizedId(baseUri)}`) : this.joi.link('/');
171
+ }
172
+
173
+ resolvedSchema = this.resolve(this.resolveReference(schema.$ref, baseUri), baseUri);
174
+ } else {
175
+ const partialSchemas = [];
176
+ if (schema.type) {
177
+ partialSchemas.push(this.resolveType(schema, baseUri));
178
+ } else if (schema.properties) {
179
+ // if no type is specified, just properties
180
+ partialSchemas.push(this.object(schema, baseUri))
181
+ } else if (schema.format) {
182
+ // if no type is specified, just format
183
+ partialSchemas.push(this.string(schema))
184
+ } else if (schema.enum) {
185
+ // If no type is specified, just enum
186
+ partialSchemas.push(this.joi.any().valid(...schema.enum).example(schema.enum[0]));
187
+ } else if (schema.const) {
188
+ // Constant value
189
+ partialSchemas.push(this.getValueJoiType(schema.const).valid(schema.const));
190
+ }
191
+ if (schema.anyOf) {
192
+ partialSchemas.push(this.resolveAnyOf(schema, baseUri));
193
+ }
194
+ if (schema.allOf) {
195
+ partialSchemas.push(this.resolveAllOf(schema, baseUri));
196
+ }
197
+ if (schema.oneOf) {
198
+ partialSchemas.push(this.resolveOneOf(schema, baseUri));
199
+ }
200
+ if (schema.not) {
201
+ partialSchemas.push(this.resolveNot(schema, baseUri));
202
+ }
203
+ if (partialSchemas.length === 0) {
204
+ //Fall through to whatever.
205
+ //eslint-disable-next-line no-console
206
+ console.warn('WARNING: schema missing a \'type\' or \'$ref\' or \'enum\': \n%s', JSON.stringify(schema, null, 2));
207
+ //TODO: Handle better
208
+ partialSchemas.push(this.joi.any());
209
+ }
210
+ resolvedSchema = partialSchemas.length === 1 ? partialSchemas[0] : this.joi.alternatives(partialSchemas).match('all');
211
+ }
212
+
213
+ if (this.refineSchema) {
214
+ resolvedSchema = this.refineSchema(resolvedSchema, schema);
215
+ }
216
+
217
+ if (this.useDefaults && schema.default !== undefined) {
218
+ resolvedSchema = resolvedSchema.default(schema.default)
219
+ }
220
+
221
+ if (schemaId) {
222
+ resolvedSchema = resolvedSchema.id(normalizedId(schemaId));
223
+ this.joiSharedSchemas.set(schemaId, resolvedSchema);
224
+ }
225
+
226
+ if (schema.$anchor) {
227
+ this.joiSharedSchemas.set(`${baseUri}#${schema.$anchor}`, resolvedSchema);
228
+ }
229
+
230
+ return resolvedSchema;
231
+ }
232
+
233
+ resolveReference(value, baseUri = '') {
234
+ debug('----- Resolving schema reference: %s with baseUri: %s ----- ', value, baseUri);
235
+ debug('Registered JOI schema for shared: %f', () => {
236
+ return JSON.stringify(mapToObj(this.joiSharedSchemas), null, 2);
237
+ });
238
+ const hashIdx = value.indexOf('#');
239
+ let refSchema;
240
+
241
+ if (hashIdx === -1) {
242
+ // Locate through $ref: 'refId'
243
+ // debug('# Resolving reference through id: %s', value);
244
+ refSchema = this.joiSharedSchemas.get(value);
245
+ } else {
246
+ const id = value.substring(0, hashIdx);
247
+ const path = value.substring(hashIdx + 1);
248
+
249
+ const canonicalURI = id ? value : `${baseUri}${value}`;
250
+
251
+ if (canonicalURI.indexOf('/') === -1) {
252
+ // Locate through $ref: [baseUri]#anchorSchema
253
+ // debug('# Resolving reference through $anchor: %s', canonicalURI);
254
+ refSchema = this.joiSharedSchemas.get(canonicalURI);
255
+ } else if (canonicalURI.indexOf('/properties') === -1) {
256
+ // Locate through $ref: [baseUri]#/$defs/shared
257
+ // debug('# Resolving reference through direct canonicalURI: %s', canonicalURI);
258
+ refSchema = this.joiSharedSchemas.get(canonicalURI);
259
+ } else {
260
+ // Locate through $ref: [baseUri]#/$defs/shared/properties/level1 or [baseUri]#/properties/product
261
+ // Can only get raw schema and build Joi again because it might not completely built yet
262
+ // debug('# Resolving reference through relative path: baseUri - %s; id - %s; path - %s', baseUri, id, path);
263
+
264
+ const paths = path.split('/');
265
+ refSchema = this.subSchemas[id || baseUri];
266
+
267
+ while (paths.length > 0 && refSchema) {
268
+ if (paths[0]) {
269
+ refSchema = refSchema[paths[0]];
270
+ }
271
+ paths.splice(0, 1);
272
+ }
273
+ }
274
+ }
275
+
276
+ Hoek.assert(refSchema, `Can not find schema reference: ${value} with baseUri: ${baseUri}`);
277
+
278
+ return refSchema;
279
+ }
280
+
281
+ resolveType(schema, baseUri) {
282
+ let joischema;
283
+
284
+ const typeDefinitionMap = {
285
+ title: 'label',
286
+ default: 'default'
287
+ };
288
+
289
+ const joitype = (type, format) => {
290
+ let joischema;
291
+
292
+ if (this.refineType) {
293
+ type = this.refineType(type, format);
294
+ }
295
+
296
+ switch (type) {
297
+ case 'array':
298
+ joischema = this.array(schema, baseUri);
299
+ break;
300
+ case 'boolean':
301
+ joischema = this.joi.boolean();
302
+ break;
303
+ case 'integer':
304
+ case 'number':
305
+ joischema = this.number(schema);
306
+ break;
307
+ case 'object':
308
+ joischema = this.object(schema, baseUri);
309
+ break;
310
+ case 'string':
311
+ joischema = this.string(schema);
312
+ break;
313
+ case 'null':
314
+ joischema = this.joi.any().valid(null);
315
+ break;
316
+ default:
317
+ joischema = this.joi.types()[type];
318
+ }
319
+
320
+ Hoek.assert(joischema, 'Could not resolve type: ' + schema.type + '.');
321
+
322
+ return joischema.strict(this.strictMode);
323
+ }
324
+
325
+ if (Array.isArray(schema.type)) {
326
+ const schemas = [];
327
+
328
+ for (let i = 0; i < schema.type.length; i++) {
329
+ schemas.push(joitype(schema.type[i], schema.format));
330
+ }
331
+
332
+ joischema = this.joi.alternatives(schemas);
333
+ } else {
334
+ joischema = joitype(schema.type, schema.format);
335
+ }
336
+
337
+ Object.keys(typeDefinitionMap).forEach(function (key) {
338
+ if (schema[key] !== undefined) {
339
+ joischema = joischema[typeDefinitionMap[key]](schema[key]);
340
+ }
341
+ });
342
+
343
+ let desc = schema.description;
344
+ if (this.refineDescription) {
345
+ desc = this.refineDescription(schema);
346
+ }
347
+ if (desc) {
348
+ joischema = joischema.description(desc);
349
+ }
350
+
351
+ let example;
352
+ if (schema.examples && schema.examples.length > 0) {
353
+ example = schema.examples[0];
354
+ }
355
+ if (!example && typeof schema.default !== 'undefined') {
356
+ example = schema.default;
357
+ }
358
+ if (!example && schema.enum && schema.enum.length > 0) {
359
+ example = schema.enum[0];
360
+ }
361
+ if (example) {
362
+ joischema = joischema.example(example);
363
+ }
364
+
365
+ return joischema;
366
+ }
367
+
368
+ resolveOneOf(schema, baseUri) {
369
+ Hoek.assert(Array.isArray(schema.oneOf), 'Expected oneOf to be an array.');
370
+
371
+ return this.joi.alternatives(schema.oneOf.map(schema => this.resolve(schema, baseUri))).match('one');
372
+ }
373
+
374
+ resolveAnyOf(schema, baseUri) {
375
+ Hoek.assert(Array.isArray(schema.anyOf), 'Expected anyOf to be an array.');
376
+
377
+ return this.joi.alternatives(schema.anyOf.map(schema => this.resolve(schema, baseUri))).match('any');
378
+ }
379
+
380
+ resolveAllOf(schema, baseUri) {
381
+ Hoek.assert(Array.isArray(schema.allOf), 'Expected allOf to be an array.');
382
+
383
+ return this.joi.alternatives(schema.allOf.map(schema => this.resolve(schema, baseUri))).match('all');
384
+ }
385
+
386
+ resolveNot(schema, baseUri) {
387
+ Hoek.assert(isObject(schema.not), 'Expected Not to be an object.');
388
+
389
+ return this.joi.alternatives().conditional(
390
+ '.',
391
+ {
392
+ not: this.resolve(schema.not, baseUri),
393
+ then: this.joi.any(),
394
+ otherwise: this.joi.any().forbidden()
395
+ }
396
+ );
397
+ }
398
+
399
+ object(schema, baseUri) {
400
+
401
+ const resolveproperties = () => {
402
+ const schemas = {};
403
+
404
+ if (!isObject(schema.properties)) {
405
+ return;
406
+ }
407
+
408
+ Object.keys(schema.properties).forEach((key) => {
409
+ const property = schema.properties[key];
410
+
411
+ let joischema = this.resolve(property, baseUri);
412
+
413
+ if (Array.isArray(schema.required) && !!~schema.required.indexOf(key)) {
414
+ joischema = joischema.required();
415
+ } else if (this.allowNull) {
416
+ joischema = joischema.allow(null);
417
+ }
418
+
419
+ schemas[key] = joischema;
420
+ });
421
+
422
+ return schemas;
423
+ }
424
+
425
+ let joischema = this.joi.object(resolveproperties(schema));
426
+
427
+ if (isObject(schema.additionalProperties)) {
428
+ joischema = joischema.pattern(/^/, this.resolve(schema.additionalProperties, baseUri));
429
+ } else {
430
+ joischema = joischema.unknown(schema.additionalProperties !== false);
431
+ }
432
+
433
+ isNumber(schema.minProperties) && (joischema = joischema.min(schema.minProperties));
434
+ isNumber(schema.maxProperties) && (joischema = joischema.max(schema.maxProperties));
435
+
436
+ return joischema;
437
+ }
438
+
439
+ array(schema, baseUri) {
440
+ let joischema = this.joi.array();
441
+ let items;
442
+
443
+ const resolveAsArray = (value) => {
444
+ if (Array.isArray(value)) {
445
+ // found an array, thus its _per type_
446
+ return value.map((v) => this.resolve(v, baseUri));
447
+ }
448
+ // it's a single entity, so just resolve it normally
449
+ return [this.resolve(value, baseUri)];
450
+ }
451
+
452
+ if (schema.items) {
453
+ items = resolveAsArray(schema.items);
454
+
455
+ joischema = joischema.items(...items);
456
+ } else if (schema.ordered) {
457
+ items = resolveAsArray(schema.ordered);
458
+ joischema = joischema.ordered(...items);
459
+ }
460
+
461
+ if (items && schema.additionalItems === false) {
462
+ joischema = joischema.max(items.length);
463
+ }
464
+
465
+ isNumber(schema.minItems) && (joischema = joischema.min(schema.minItems));
466
+ isNumber(schema.maxItems) && (joischema = joischema.max(schema.maxItems));
467
+
468
+ if (schema.uniqueItems) {
469
+ joischema = joischema.unique();
470
+ }
471
+ if (schema.contains) {
472
+ joischema = joischema.has(this.resolve(schema.contains, baseUri));
473
+ }
474
+
475
+ return joischema;
476
+ }
477
+
478
+ number(schema) {
479
+ let joischema = this.joi.number();
480
+
481
+ if (schema.type === 'integer') {
482
+ joischema = joischema.integer();
483
+ }
484
+
485
+ isNumber(schema.minimum) && (joischema = joischema.min(schema.minimum));
486
+ isNumber(schema.maximum) && (joischema = joischema.max(schema.maximum));
487
+ isNumber(schema.exclusiveMinimum) && (joischema = joischema.greater(schema.exclusiveMinimum));
488
+ isNumber(schema.exclusiveMaximum) && (joischema = joischema.less(schema.exclusiveMaximum));
489
+ isNumber(schema.multipleOf) && schema.multipleOf !== 0 && (joischema = joischema.multiple(schema.multipleOf));
490
+
491
+ return joischema;
492
+ }
493
+
494
+ string(schema) {
495
+ let joischema = this.joi.string();
496
+
497
+ const dateRegex = '(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])';
498
+ const timeRegex = '([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(.[0-9]+)?(Z|(\\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))';
499
+ const dateTimeRegex = dateRegex + 'T' + timeRegex;
500
+
501
+ if (schema.enum) {
502
+ return this.joi.string().valid(...schema.enum);
503
+ }
504
+
505
+ switch (schema.format) {
506
+ case 'date':
507
+ return joischema.regex(new RegExp('^' + dateRegex + '$', 'i'), 'JsonSchema date format');
508
+ case 'time':
509
+ return joischema.regex(new RegExp('^' + timeRegex + '$', 'i'), 'JsonSchema time format');
510
+ case 'date-time':
511
+ return joischema.regex(new RegExp('^' + dateTimeRegex + '$', 'i'), 'JsonSchema date-time format');
512
+ case 'binary':
513
+ joischema = this.binary(schema);
514
+ break;
515
+ case 'email':
516
+ return joischema.email();
517
+ case 'hostname':
518
+ return joischema.hostname();
519
+ case 'ipv4':
520
+ return joischema.ip({
521
+ version: ['ipv4']
522
+ });
523
+ case 'ipv6':
524
+ return joischema.ip({
525
+ version: ['ipv6']
526
+ });
527
+ case 'uri':
528
+ return joischema.uri();
529
+ case 'byte':
530
+ joischema = joischema.base64();
531
+ break;
532
+ case 'uuid':
533
+ return joischema.guid({ version: ['uuidv4'] });
534
+ case 'guid':
535
+ return joischema.guid();
536
+ }
537
+ return this.regularString(schema, joischema);
538
+ }
539
+
540
+ regularString(schema, joischema) {
541
+ schema.pattern && (joischema = joischema.regex(new RegExp(schema.pattern)));
542
+
543
+ if (typeof schema.minLength === 'undefined') {
544
+ schema.minLength = 0;
545
+ }
546
+
547
+ if (schema.minLength === 0 && !schema.pattern && !schema.format) {
548
+ joischema = joischema.allow('');
549
+ }
550
+
551
+ isNumber(schema.minLength) && (joischema = joischema.min(schema.minLength));
552
+ isNumber(schema.maxLength) && (joischema = joischema.max(schema.maxLength));
553
+ return joischema;
554
+ }
555
+
556
+ binary(schema) {
557
+ let joischema = this.joi.binary();
558
+ isNumber(schema.minLength) && (joischema = joischema.min(schema.minLength));
559
+ isNumber(schema.maxLength) && (joischema = joischema.max(schema.maxLength));
560
+ return joischema;
561
+ }
562
+
563
+ getValueJoiType(value) {
564
+ let joiType;
565
+ switch (typeof value) {
566
+ case 'string':
567
+ joiType = this.joi.string();
568
+ break;
569
+ case 'number':
570
+ joiType = this.joi.number();
571
+ break;
572
+ case 'boolean':
573
+ joiType = this.joi.boolean();
574
+ break;
575
+ default:
576
+ joiType = this.joi.any();
577
+ }
578
+ return joiType;
579
+ }
580
+ }
581
+
582
+ module.exports = SchemaResolver;
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "json-2-joi",
3
+ "version": "1.0.0",
4
+ "license": "Apache 2.0",
5
+ "description": "Converts json-schema to Joi schema.",
6
+ "main": "./index.js",
7
+ "scripts": {
8
+ "test": "tape test/*.js",
9
+ "cover": "nyc --reporter=lcov --lines 100 npm test && nyc report",
10
+ "lint": "eslint index.js lib/resolver.js"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git://github.com/kenspirit/json-2-joi.git"
15
+ },
16
+ "engines": {
17
+ "node": ">=12"
18
+ },
19
+ "keywords": [
20
+ "json-to-joi",
21
+ "json-2-joi",
22
+ "joi",
23
+ "json-schema",
24
+ "json",
25
+ "schema",
26
+ "validation",
27
+ "conversion",
28
+ "hapi",
29
+ "enjoi"
30
+ ],
31
+ "author": "Ken Chen <chengusky@gmail.com>",
32
+ "bugs": {
33
+ "url": "https://github.com/kenspirit/json-2-joi/issues"
34
+ },
35
+ "homepage": "https://github.com/kenspirit/json-2-joi",
36
+ "dependencies": {
37
+ "@hapi/bourne": "^3.0.0",
38
+ "@hapi/hoek": "^9.3.0",
39
+ "debug": "^4.3.4"
40
+ },
41
+ "peerDependencies": {
42
+ "joi": "^17.6.0"
43
+ },
44
+ "devDependencies": {
45
+ "joi": "^17.6.0",
46
+ "eslint": "^6.8.0",
47
+ "nyc": "^15.1.0",
48
+ "tape": "^5.5.3"
49
+ },
50
+ "files": [
51
+ "lib/**/*.js",
52
+ "index.js"
53
+ ]
54
+ }