Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/vine/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

import { Compiler, refsBuilder } from '@vinejs/compiler'
import type { StandardSchemaV1 } from '@standard-schema/spec'
import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec'
import type { MessagesProviderContact, Refs, RootNode } from '@vinejs/compiler/types'

import { messages } from '../defaults.js'
Expand Down Expand Up @@ -254,9 +254,20 @@ export class VineValidator<
return this.#jsonSchema
}

readonly '~standard': StandardSchemaV1.Props<Schema[typeof ITYPE], Schema[typeof OTYPE]> = {
readonly '~standard': StandardSchemaV1.Props<Schema[typeof ITYPE], Schema[typeof OTYPE]> &
StandardJSONSchemaV1.Props<Schema[typeof ITYPE], Schema[typeof OTYPE]> = {
version: 1,
vendor: 'vinejs',

jsonSchema: {
input: () => {
return this.toJSONSchema() as Record<string, unknown>
},
output: () => {
throw new Error('Vine.js does not support creating validators using JSON Schema.')
},
},

validate: async (data: unknown) => {
const [error, result] = await this.tryValidate(data, {} as any)
if (result) {
Expand Down
40 changes: 40 additions & 0 deletions tests/integration/json_schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import vine from '../../index.js'
import Ajv from 'ajv'
import { type SchemaTypes } from '../../src/types.js'
import { inspect } from 'node:util'
import { type StandardJSONSchemaV1 } from '@standard-schema/spec'

const ajv = new Ajv()

Expand Down Expand Up @@ -669,3 +670,42 @@ test.group('JsonSchema', () => {
})
.tags(['@literal'])
})

test.group('JsonSchema | StandardJsonSchema', () => {
test('should respect StandardJSONSchemaV1 type', ({ expectTypeOf }) => {
const validator = vine.create({
name: vine.string(),
email: vine.string().email(),
})

expectTypeOf<StandardJSONSchemaV1>(validator)
})

test('convert to json-schema as per standard schema spec', ({ assert }) => {
const validator = vine.create({
name: vine.string(),
email: vine.string().email(),
})

const result = validator['~standard'].jsonSchema.input({ target: 'draft-2020-12' })

assert.deepEqual(result, {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
},
additionalProperties: false,
required: ['name', 'email'],
})
})

test('convert from json-schema as per standard schema spec should throw', ({ assert }) => {
const validator = vine.create({
name: vine.string(),
email: vine.string().email(),
})

assert.throws(() => validator['~standard'].jsonSchema.output({ target: 'draft-2020-12' }))
})
})