@amritk/adapters 0.2.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/dist/adapter.d.ts +22 -0
- package/dist/adapter.js +0 -0
- package/dist/effect-to-json-schema.d.ts +11 -0
- package/dist/effect-to-json-schema.js +66264 -0
- package/dist/get-adapter.d.ts +11 -0
- package/dist/get-adapter.js +81915 -0
- package/dist/source-format.d.ts +11 -0
- package/dist/source-format.js +0 -0
- package/dist/typebox-to-json-schema.d.ts +13 -0
- package/dist/typebox-to-json-schema.js +61 -0
- package/dist/valibot-to-json-schema.d.ts +12 -0
- package/dist/valibot-to-json-schema.js +672 -0
- package/dist/zod-to-json-schema.d.ts +12 -0
- package/dist/zod-to-json-schema.js +14936 -0
- package/package.json +101 -0
- package/src/adapter.ts +24 -0
- package/src/effect-to-json-schema.test.ts +74 -0
- package/src/effect-to-json-schema.ts +57 -0
- package/src/get-adapter.test.ts +36 -0
- package/src/get-adapter.ts +52 -0
- package/src/source-format.ts +11 -0
- package/src/typebox-to-json-schema.test.ts +121 -0
- package/src/typebox-to-json-schema.ts +79 -0
- package/src/valibot-to-json-schema.test.ts +100 -0
- package/src/valibot-to-json-schema.ts +77 -0
- package/src/zod-to-json-schema.test.ts +114 -0
- package/src/zod-to-json-schema.ts +87 -0
package/package.json
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@amritk/adapters",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Convert schemas from external libraries (TypeBox, Zod, ...) into JSON Schema for mjst.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "amritk",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"json-schema",
|
|
10
|
+
"typescript",
|
|
11
|
+
"typebox",
|
|
12
|
+
"zod",
|
|
13
|
+
"valibot",
|
|
14
|
+
"effect",
|
|
15
|
+
"adapter",
|
|
16
|
+
"mjst"
|
|
17
|
+
],
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/amritk/mjst.git",
|
|
21
|
+
"directory": "packages/adapters"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/amritk/mjst/tree/main/packages/adapters#readme",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/amritk/mjst/issues"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"src"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "bun run build:code && bun run build:types",
|
|
36
|
+
"build:code": "bun build ./src/adapter.ts ./src/source-format.ts ./src/get-adapter.ts ./src/typebox-to-json-schema.ts ./src/zod-to-json-schema.ts ./src/valibot-to-json-schema.ts ./src/effect-to-json-schema.ts --outdir=dist --root=src --target=node",
|
|
37
|
+
"build:types": "tsc -p ."
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"json-schema-typed": "catalog:",
|
|
41
|
+
"@amritk/helpers": "workspace:*"
|
|
42
|
+
},
|
|
43
|
+
"exports": {
|
|
44
|
+
"./package.json": "./package.json",
|
|
45
|
+
"./adapter": {
|
|
46
|
+
"bun": "./src/adapter.ts",
|
|
47
|
+
"default": "./dist/adapter.js",
|
|
48
|
+
"types": "./dist/adapter.d.ts"
|
|
49
|
+
},
|
|
50
|
+
"./source-format": {
|
|
51
|
+
"bun": "./src/source-format.ts",
|
|
52
|
+
"default": "./dist/source-format.js",
|
|
53
|
+
"types": "./dist/source-format.d.ts"
|
|
54
|
+
},
|
|
55
|
+
"./get-adapter": {
|
|
56
|
+
"bun": "./src/get-adapter.ts",
|
|
57
|
+
"default": "./dist/get-adapter.js",
|
|
58
|
+
"types": "./dist/get-adapter.d.ts"
|
|
59
|
+
},
|
|
60
|
+
"./typebox-to-json-schema": {
|
|
61
|
+
"bun": "./src/typebox-to-json-schema.ts",
|
|
62
|
+
"default": "./dist/typebox-to-json-schema.js",
|
|
63
|
+
"types": "./dist/typebox-to-json-schema.d.ts"
|
|
64
|
+
},
|
|
65
|
+
"./zod-to-json-schema": {
|
|
66
|
+
"bun": "./src/zod-to-json-schema.ts",
|
|
67
|
+
"default": "./dist/zod-to-json-schema.js",
|
|
68
|
+
"types": "./dist/zod-to-json-schema.d.ts"
|
|
69
|
+
},
|
|
70
|
+
"./valibot-to-json-schema": {
|
|
71
|
+
"bun": "./src/valibot-to-json-schema.ts",
|
|
72
|
+
"default": "./dist/valibot-to-json-schema.js",
|
|
73
|
+
"types": "./dist/valibot-to-json-schema.d.ts"
|
|
74
|
+
},
|
|
75
|
+
"./effect-to-json-schema": {
|
|
76
|
+
"bun": "./src/effect-to-json-schema.ts",
|
|
77
|
+
"default": "./dist/effect-to-json-schema.js",
|
|
78
|
+
"types": "./dist/effect-to-json-schema.d.ts"
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"peerDependencies": {
|
|
82
|
+
"zod": ">=4",
|
|
83
|
+
"valibot": ">=1",
|
|
84
|
+
"@valibot/to-json-schema": ">=1",
|
|
85
|
+
"effect": ">=3"
|
|
86
|
+
},
|
|
87
|
+
"peerDependenciesMeta": {
|
|
88
|
+
"zod": {
|
|
89
|
+
"optional": true
|
|
90
|
+
},
|
|
91
|
+
"valibot": {
|
|
92
|
+
"optional": true
|
|
93
|
+
},
|
|
94
|
+
"@valibot/to-json-schema": {
|
|
95
|
+
"optional": true
|
|
96
|
+
},
|
|
97
|
+
"effect": {
|
|
98
|
+
"optional": true
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
package/src/adapter.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
import type { SourceFormat } from './source-format'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Converts a schema authored in some external library into a Draft 2020-12
|
|
7
|
+
* JSON Schema, which is the single input shape the mjst generators understand.
|
|
8
|
+
*
|
|
9
|
+
* Adapters receive the already-loaded schema value (an imported module export),
|
|
10
|
+
* not a file path. Loading the module is the caller's job so adapters stay pure
|
|
11
|
+
* and trivial to unit test. When a source construct cannot be represented in
|
|
12
|
+
* JSON Schema, adapters should warn and continue on a best-effort basis rather
|
|
13
|
+
* than throw, so generation is not blocked by a single unsupported field.
|
|
14
|
+
*/
|
|
15
|
+
export type Adapter = {
|
|
16
|
+
/** The source format this adapter handles, matching the `--input` CLI flag. */
|
|
17
|
+
readonly format: SourceFormat
|
|
18
|
+
/**
|
|
19
|
+
* Convert a loaded source schema value into a JSON Schema. May be async:
|
|
20
|
+
* some adapters (e.g. Zod) dynamically import their source library to perform
|
|
21
|
+
* the conversion, so callers should always `await` the result.
|
|
22
|
+
*/
|
|
23
|
+
readonly toJSONSchema: (source: unknown) => JSONSchema | Promise<JSONSchema>
|
|
24
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { generateTypeDefinition } from '@amritk/helpers/generate-type-definition'
|
|
2
|
+
import { Schema } from 'effect'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { effectToJsonSchema } from './effect-to-json-schema'
|
|
6
|
+
|
|
7
|
+
describe('effectToJsonSchema', () => {
|
|
8
|
+
it('converts a struct with required and optional fields', async () => {
|
|
9
|
+
const schema = Schema.Struct({
|
|
10
|
+
name: Schema.String,
|
|
11
|
+
age: Schema.optional(Schema.Number),
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
const result = await effectToJsonSchema(schema)
|
|
15
|
+
|
|
16
|
+
expect(result).toMatchObject({
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
name: { type: 'string' },
|
|
20
|
+
age: { type: 'number' },
|
|
21
|
+
},
|
|
22
|
+
required: ['name'],
|
|
23
|
+
})
|
|
24
|
+
expect((result as { required: string[] }).required).not.toContain('age')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('strips the $schema dialect marker', async () => {
|
|
28
|
+
const result = await effectToJsonSchema(Schema.Struct({ name: Schema.String }))
|
|
29
|
+
expect(result).not.toHaveProperty('$schema')
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('converts arrays and nested structs', async () => {
|
|
33
|
+
const schema = Schema.Struct({
|
|
34
|
+
tags: Schema.Array(Schema.String),
|
|
35
|
+
profile: Schema.Struct({ id: Schema.String }),
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
const result = await effectToJsonSchema(schema)
|
|
39
|
+
|
|
40
|
+
expect(result).toMatchObject({
|
|
41
|
+
properties: {
|
|
42
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
43
|
+
profile: { type: 'object', properties: { id: { type: 'string' } } },
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('represents Schema.Date as its encoded string form', async () => {
|
|
49
|
+
// Effect models Schema.Date as a string-to-Date decode, so the JSON Schema
|
|
50
|
+
// (the wire representation) is a string referenced via $defs.
|
|
51
|
+
const result = await effectToJsonSchema(Schema.Struct({ when: Schema.Date }))
|
|
52
|
+
|
|
53
|
+
const json = JSON.stringify(result)
|
|
54
|
+
expect(json).toContain('"when"')
|
|
55
|
+
expect(json).toContain('string')
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('throws a helpful error for non-object input', async () => {
|
|
59
|
+
await expect(effectToJsonSchema(null)).rejects.toThrow(/expected an Effect Schema but received null/)
|
|
60
|
+
await expect(effectToJsonSchema('nope')).rejects.toThrow(/received string/)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('round-trips a plain struct through the type generator', async () => {
|
|
64
|
+
const schema = Schema.Struct({
|
|
65
|
+
id: Schema.String,
|
|
66
|
+
score: Schema.optional(Schema.Number),
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
const typeDef = generateTypeDefinition(await effectToJsonSchema(schema), 'Event')
|
|
70
|
+
|
|
71
|
+
expect(typeDef).toContain('id: string;')
|
|
72
|
+
expect(typeDef).toContain('score?: number;')
|
|
73
|
+
})
|
|
74
|
+
})
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
// Minimal structural view of `effect`'s `JSONSchema.make`, loaded at runtime so
|
|
4
|
+
// `effect` stays an optional peer dependency.
|
|
5
|
+
type Make = (schema: unknown) => Record<string, unknown>
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Resolves `effect`'s `JSONSchema.make` from a runtime import, throwing a clear
|
|
9
|
+
* error when it is missing.
|
|
10
|
+
*/
|
|
11
|
+
const loadMake = async (): Promise<Make> => {
|
|
12
|
+
let mod: Record<string, unknown>
|
|
13
|
+
try {
|
|
14
|
+
mod = (await import('effect')) as Record<string, unknown>
|
|
15
|
+
} catch {
|
|
16
|
+
throw new Error("The Effect adapter requires 'effect' to be installed in your project.")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const jsonSchema = mod['JSONSchema'] as Record<string, unknown> | undefined
|
|
20
|
+
const make = jsonSchema?.['make']
|
|
21
|
+
|
|
22
|
+
if (typeof make !== 'function') {
|
|
23
|
+
throw new Error("Effect's 'JSONSchema.make' was not found. The Effect adapter requires effect v3 or later.")
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return make as Make
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Converts an Effect `Schema` into a JSON Schema via `JSONSchema.make`.
|
|
31
|
+
*
|
|
32
|
+
* Effect models values as a decode/encode pair, so `JSONSchema.make` describes
|
|
33
|
+
* the *encoded* (wire) representation. For example `Schema.Date` decodes from a
|
|
34
|
+
* string, so it converts to a string schema rather than a runtime `Date`. We
|
|
35
|
+
* pass that representation straight through — it accurately reflects what Effect
|
|
36
|
+
* expects on the wire — only stripping the dialect marker.
|
|
37
|
+
*/
|
|
38
|
+
export const effectToJsonSchema = async (source: unknown): Promise<JSONSchema> => {
|
|
39
|
+
// Effect `Schema` values are callable, so they report as `function`, not `object`.
|
|
40
|
+
if ((typeof source !== 'object' && typeof source !== 'function') || source === null) {
|
|
41
|
+
const received = source === null ? 'null' : typeof source
|
|
42
|
+
throw new Error(`Effect adapter expected an Effect Schema but received ${received}.`)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const make = await loadMake()
|
|
46
|
+
|
|
47
|
+
let json: Record<string, unknown>
|
|
48
|
+
try {
|
|
49
|
+
json = make(source)
|
|
50
|
+
} catch (error) {
|
|
51
|
+
throw new Error(`Effect adapter failed to convert the schema. Is it a valid Effect Schema?\n${String(error)}`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
delete json['$schema']
|
|
55
|
+
|
|
56
|
+
return json as JSONSchema
|
|
57
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import * as zodModule from 'zod'
|
|
3
|
+
|
|
4
|
+
import { getAdapter } from './get-adapter'
|
|
5
|
+
|
|
6
|
+
const z = ((zodModule as Record<string, unknown>)['z'] ??
|
|
7
|
+
(zodModule as Record<string, unknown>)['default'] ??
|
|
8
|
+
zodModule) as typeof import('zod')['z']
|
|
9
|
+
|
|
10
|
+
describe('getAdapter', () => {
|
|
11
|
+
it('returns the TypeBox adapter', () => {
|
|
12
|
+
const adapter = getAdapter('typebox')
|
|
13
|
+
expect(adapter.format).toBe('typebox')
|
|
14
|
+
expect(adapter.toJSONSchema({ type: 'string' })).toEqual({ type: 'string' })
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('returns the Zod adapter, which converts asynchronously', async () => {
|
|
18
|
+
const adapter = getAdapter('zod')
|
|
19
|
+
expect(adapter.format).toBe('zod')
|
|
20
|
+
|
|
21
|
+
const result = await adapter.toJSONSchema(z.object({ name: z.string() }))
|
|
22
|
+
expect(result).toMatchObject({ type: 'object', properties: { name: { type: 'string' } } })
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('returns the Valibot adapter', () => {
|
|
26
|
+
expect(getAdapter('valibot').format).toBe('valibot')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('returns the Effect adapter', () => {
|
|
30
|
+
expect(getAdapter('effect').format).toBe('effect')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('throws an actionable error for the json format (handled directly by the CLI)', () => {
|
|
34
|
+
expect(() => getAdapter('json')).toThrow(/No adapter is available for input format 'json'/)
|
|
35
|
+
})
|
|
36
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Adapter } from './adapter'
|
|
2
|
+
import { effectToJsonSchema } from './effect-to-json-schema'
|
|
3
|
+
import type { SourceFormat } from './source-format'
|
|
4
|
+
import { typeboxToJsonSchema } from './typebox-to-json-schema'
|
|
5
|
+
import { valibotToJsonSchema } from './valibot-to-json-schema'
|
|
6
|
+
import { zodToJsonSchema } from './zod-to-json-schema'
|
|
7
|
+
|
|
8
|
+
const typeboxAdapter: Adapter = {
|
|
9
|
+
format: 'typebox',
|
|
10
|
+
toJSONSchema: typeboxToJsonSchema,
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const zodAdapter: Adapter = {
|
|
14
|
+
format: 'zod',
|
|
15
|
+
toJSONSchema: zodToJsonSchema,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const valibotAdapter: Adapter = {
|
|
19
|
+
format: 'valibot',
|
|
20
|
+
toJSONSchema: valibotToJsonSchema,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const effectAdapter: Adapter = {
|
|
24
|
+
format: 'effect',
|
|
25
|
+
toJSONSchema: effectToJsonSchema,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolves the adapter for a non-JSON source format.
|
|
30
|
+
*
|
|
31
|
+
* Only formats with an implemented adapter resolve. The `'json'` format never
|
|
32
|
+
* reaches here — the CLI reads JSON Schema files directly without an adapter —
|
|
33
|
+
* and formats that are named but not yet built throw a clear, actionable error
|
|
34
|
+
* so the CLI can fail fast with guidance instead of a cryptic crash.
|
|
35
|
+
*/
|
|
36
|
+
export const getAdapter = (format: SourceFormat): Adapter => {
|
|
37
|
+
switch (format) {
|
|
38
|
+
case 'typebox':
|
|
39
|
+
return typeboxAdapter
|
|
40
|
+
case 'zod':
|
|
41
|
+
return zodAdapter
|
|
42
|
+
case 'valibot':
|
|
43
|
+
return valibotAdapter
|
|
44
|
+
case 'effect':
|
|
45
|
+
return effectAdapter
|
|
46
|
+
default:
|
|
47
|
+
throw new Error(
|
|
48
|
+
`No adapter is available for input format '${format}'. ` +
|
|
49
|
+
`Supported: 'typebox', 'zod', 'valibot', 'effect'. Use --input json for plain JSON Schema files.`,
|
|
50
|
+
)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema authoring formats mjst can ingest.
|
|
3
|
+
*
|
|
4
|
+
* `'json'` is the built-in default: a plain JSON Schema file read from disk and
|
|
5
|
+
* handed straight to the generators. The others name external libraries whose
|
|
6
|
+
* schemas are first converted to JSON Schema by a matching adapter.
|
|
7
|
+
*
|
|
8
|
+
* A format may appear here before its adapter exists — `getAdapter` is the
|
|
9
|
+
* source of truth for what is actually implemented today.
|
|
10
|
+
*/
|
|
11
|
+
export type SourceFormat = 'json' | 'typebox' | 'zod' | 'valibot' | 'effect'
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { Type } from '@sinclair/typebox'
|
|
2
|
+
import { describe, expect, it } from 'vitest'
|
|
3
|
+
|
|
4
|
+
import { typeboxToJsonSchema } from './typebox-to-json-schema'
|
|
5
|
+
|
|
6
|
+
describe('typeboxToJsonSchema', () => {
|
|
7
|
+
it('round-trips a real TypeBox schema, mapping Date and bigint', () => {
|
|
8
|
+
const schema = Type.Object({
|
|
9
|
+
id: Type.String(),
|
|
10
|
+
when: Type.Date(),
|
|
11
|
+
balance: Type.BigInt(),
|
|
12
|
+
nickname: Type.Optional(Type.String()),
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
expect(typeboxToJsonSchema(schema)).toEqual({
|
|
16
|
+
type: 'object',
|
|
17
|
+
required: ['id', 'when', 'balance'],
|
|
18
|
+
properties: {
|
|
19
|
+
id: { type: 'string' },
|
|
20
|
+
when: { 'x-mjst': { instanceOf: 'Date' } },
|
|
21
|
+
balance: { 'x-mjst': { primitive: 'bigint' } },
|
|
22
|
+
nickname: { type: 'string' },
|
|
23
|
+
},
|
|
24
|
+
})
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('strips TypeBox symbol keys and returns plain JSON Schema', () => {
|
|
28
|
+
// Mimic a TypeBox object schema: a plain JSON-Schema-shaped object that also
|
|
29
|
+
// carries internal symbol keys. The symbols must not survive conversion.
|
|
30
|
+
const Kind = Symbol.for('TypeBox.Kind')
|
|
31
|
+
const typeboxSchema = {
|
|
32
|
+
[Kind]: 'Object',
|
|
33
|
+
type: 'object',
|
|
34
|
+
properties: {
|
|
35
|
+
name: { [Kind]: 'String', type: 'string' },
|
|
36
|
+
age: { [Kind]: 'Number', type: 'number' },
|
|
37
|
+
},
|
|
38
|
+
required: ['name'],
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const result = typeboxToJsonSchema(typeboxSchema)
|
|
42
|
+
|
|
43
|
+
expect(result).toEqual({
|
|
44
|
+
type: 'object',
|
|
45
|
+
properties: {
|
|
46
|
+
name: { type: 'string' },
|
|
47
|
+
age: { type: 'number' },
|
|
48
|
+
},
|
|
49
|
+
required: ['name'],
|
|
50
|
+
})
|
|
51
|
+
expect(Object.getOwnPropertySymbols(result)).toHaveLength(0)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('preserves nested structures and arrays', () => {
|
|
55
|
+
const schema = {
|
|
56
|
+
type: 'object',
|
|
57
|
+
properties: {
|
|
58
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
59
|
+
meta: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
expect(typeboxToJsonSchema(schema)).toEqual(schema)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('rewrites TypeBox Date into an x-mjst instanceOf hint', () => {
|
|
67
|
+
const schema = {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
createdAt: { type: 'Date' },
|
|
71
|
+
name: { type: 'string' },
|
|
72
|
+
},
|
|
73
|
+
required: ['createdAt'],
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
expect(typeboxToJsonSchema(schema)).toEqual({
|
|
77
|
+
type: 'object',
|
|
78
|
+
properties: {
|
|
79
|
+
createdAt: { 'x-mjst': { instanceOf: 'Date' } },
|
|
80
|
+
name: { type: 'string' },
|
|
81
|
+
},
|
|
82
|
+
required: ['createdAt'],
|
|
83
|
+
})
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
it('leaves unmapped extended types unchanged', () => {
|
|
87
|
+
const schema = { type: 'object', properties: { buf: { type: 'Uint8Array' } } }
|
|
88
|
+
expect(typeboxToJsonSchema(schema)).toEqual(schema)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('rewrites TypeBox bigint into an x-mjst primitive hint', () => {
|
|
92
|
+
const schema = {
|
|
93
|
+
type: 'object',
|
|
94
|
+
properties: { balance: { type: 'bigint' }, name: { type: 'string' } },
|
|
95
|
+
required: ['balance'],
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
expect(typeboxToJsonSchema(schema)).toEqual({
|
|
99
|
+
type: 'object',
|
|
100
|
+
properties: {
|
|
101
|
+
balance: { 'x-mjst': { primitive: 'bigint' } },
|
|
102
|
+
name: { type: 'string' },
|
|
103
|
+
},
|
|
104
|
+
required: ['balance'],
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('preserves a hand-authored x-mjst brand keyword', () => {
|
|
109
|
+
const schema = {
|
|
110
|
+
type: 'object',
|
|
111
|
+
properties: { id: { type: 'string', 'x-mjst': { brand: 'UserId' } } },
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
expect(typeboxToJsonSchema(schema)).toEqual(schema)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it('throws a helpful error for non-object input', () => {
|
|
118
|
+
expect(() => typeboxToJsonSchema(null)).toThrow(/expected a schema object but received null/)
|
|
119
|
+
expect(() => typeboxToJsonSchema('nope')).toThrow(/received string/)
|
|
120
|
+
})
|
|
121
|
+
})
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension'
|
|
2
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
3
|
+
|
|
4
|
+
// The seven core JSON Schema 2020-12 types. Anything else in a `type` slot is a
|
|
5
|
+
// TypeBox extended type with no native JSON Schema equivalent.
|
|
6
|
+
const JSON_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null'])
|
|
7
|
+
|
|
8
|
+
// Maps a TypeBox extended `type` string to the runtime class an `x-mjst`
|
|
9
|
+
// instanceOf hint should reference. Add entries here as more extended types
|
|
10
|
+
// gain generator support.
|
|
11
|
+
const EXTENDED_TYPE_TO_INSTANCE: Record<string, string> = {
|
|
12
|
+
Date: 'Date',
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Maps a TypeBox extended `type` string to a non-JSON `x-mjst` primitive hint
|
|
16
|
+
// (e.g. Type.BigInt() emits `{ type: 'bigint' }`).
|
|
17
|
+
const EXTENDED_TYPE_TO_PRIMITIVE: Record<string, string> = {
|
|
18
|
+
bigint: 'bigint',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Recursively rewrites TypeBox extended types into an `x-mjst` instanceOf hint.
|
|
23
|
+
*
|
|
24
|
+
* TypeBox emits non-standard `type` strings for runtime classes (e.g.
|
|
25
|
+
* `Type.Date()` produces `{ type: 'Date' }`). We drop the bogus `type` and
|
|
26
|
+
* record the class under `x-mjst` so the generators can emit the right
|
|
27
|
+
* TypeScript type and `instanceof` checks. Extended types we do not yet map are
|
|
28
|
+
* left untouched with a warning, preserving a permissive best-effort fallback.
|
|
29
|
+
*/
|
|
30
|
+
const rewriteExtendedTypes = (value: unknown): unknown => {
|
|
31
|
+
if (Array.isArray(value)) return value.map(rewriteExtendedTypes)
|
|
32
|
+
if (typeof value !== 'object' || value === null) return value
|
|
33
|
+
|
|
34
|
+
const source = value as Record<string, unknown>
|
|
35
|
+
const result: Record<string, unknown> = {}
|
|
36
|
+
for (const [key, val] of Object.entries(source)) {
|
|
37
|
+
result[key] = rewriteExtendedTypes(val)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const type = result['type']
|
|
41
|
+
if (typeof type === 'string' && !JSON_SCHEMA_TYPES.has(type)) {
|
|
42
|
+
const primitive = EXTENDED_TYPE_TO_PRIMITIVE[type]
|
|
43
|
+
const instanceOf = EXTENDED_TYPE_TO_INSTANCE[type]
|
|
44
|
+
if (primitive) {
|
|
45
|
+
delete result['type']
|
|
46
|
+
result[MJST_EXTENSION_KEY] = { primitive }
|
|
47
|
+
} else if (instanceOf) {
|
|
48
|
+
delete result['type']
|
|
49
|
+
result[MJST_EXTENSION_KEY] = { instanceOf }
|
|
50
|
+
} else {
|
|
51
|
+
console.warn(`[mjst] TypeBox type '${type}' has no JSON Schema or x-mjst mapping; leaving it unchanged.`)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return result
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* TypeBox schemas are already JSON Schema objects at runtime, but they carry
|
|
60
|
+
* non-enumerable symbol keys (`Kind`, `Optional`, ...) that TypeBox uses for its
|
|
61
|
+
* own type machinery. A JSON round-trip drops those symbols (and any `undefined`
|
|
62
|
+
* values), leaving a clean, plain JSON Schema. We then rewrite TypeBox's
|
|
63
|
+
* extended types (Date, ...) into `x-mjst` hints the generators understand.
|
|
64
|
+
*
|
|
65
|
+
* We deliberately do not import TypeBox here: the conversion only touches the
|
|
66
|
+
* plain-object shape, so TypeBox stays an optional peer dependency used solely
|
|
67
|
+
* by the consumer's schema module, never by mjst itself.
|
|
68
|
+
*/
|
|
69
|
+
export const typeboxToJsonSchema = (source: unknown): JSONSchema => {
|
|
70
|
+
if (typeof source !== 'object' || source === null) {
|
|
71
|
+
const received = source === null ? 'null' : typeof source
|
|
72
|
+
throw new Error(`TypeBox adapter expected a schema object but received ${received}.`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Boundary cast: JSON.parse yields `unknown`, and the round-tripped, rewritten
|
|
76
|
+
// TypeBox schema is a valid JSON Schema by construction.
|
|
77
|
+
const sanitized: unknown = JSON.parse(JSON.stringify(source))
|
|
78
|
+
return rewriteExtendedTypes(sanitized) as JSONSchema
|
|
79
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { generateTypeDefinition } from '@amritk/helpers/generate-type-definition'
|
|
2
|
+
import * as v from 'valibot'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { valibotToJsonSchema } from './valibot-to-json-schema'
|
|
6
|
+
|
|
7
|
+
describe('valibotToJsonSchema', () => {
|
|
8
|
+
it('converts an object with required and optional fields', async () => {
|
|
9
|
+
const schema = v.object({
|
|
10
|
+
name: v.string(),
|
|
11
|
+
age: v.optional(v.number()),
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
const result = await valibotToJsonSchema(schema)
|
|
15
|
+
|
|
16
|
+
expect(result).toMatchObject({
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
name: { type: 'string' },
|
|
20
|
+
age: { type: 'number' },
|
|
21
|
+
},
|
|
22
|
+
required: ['name'],
|
|
23
|
+
})
|
|
24
|
+
expect((result as { required: string[] }).required).not.toContain('age')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('converts picklists to a string schema with an enum list', async () => {
|
|
28
|
+
const result = await valibotToJsonSchema(v.object({ role: v.picklist(['admin', 'user']) }))
|
|
29
|
+
|
|
30
|
+
expect(result).toMatchObject({
|
|
31
|
+
properties: { role: { type: 'string', enum: ['admin', 'user'] } },
|
|
32
|
+
})
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('converts arrays and nested objects', async () => {
|
|
36
|
+
const schema = v.object({
|
|
37
|
+
tags: v.array(v.string()),
|
|
38
|
+
profile: v.object({ id: v.string() }),
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
const result = await valibotToJsonSchema(schema)
|
|
42
|
+
|
|
43
|
+
expect(result).toMatchObject({
|
|
44
|
+
properties: {
|
|
45
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
46
|
+
profile: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('strips the $schema dialect marker', async () => {
|
|
52
|
+
const result = await valibotToJsonSchema(v.object({ name: v.string() }))
|
|
53
|
+
expect(result).not.toHaveProperty('$schema')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('maps v.date() to an x-mjst instanceOf Date hint', async () => {
|
|
57
|
+
const result = await valibotToJsonSchema(v.object({ when: v.date(), name: v.string() }))
|
|
58
|
+
|
|
59
|
+
expect(result).toMatchObject({
|
|
60
|
+
properties: {
|
|
61
|
+
when: { 'x-mjst': { instanceOf: 'Date' } },
|
|
62
|
+
name: { type: 'string' },
|
|
63
|
+
},
|
|
64
|
+
})
|
|
65
|
+
expect((result as { properties: { when: Record<string, unknown> } }).properties.when).not.toHaveProperty('type')
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('maps v.bigint() to an x-mjst primitive bigint hint', async () => {
|
|
69
|
+
const result = await valibotToJsonSchema(v.object({ balance: v.bigint(), name: v.string() }))
|
|
70
|
+
|
|
71
|
+
expect(result).toMatchObject({
|
|
72
|
+
properties: {
|
|
73
|
+
balance: { 'x-mjst': { primitive: 'bigint' } },
|
|
74
|
+
name: { type: 'string' },
|
|
75
|
+
},
|
|
76
|
+
})
|
|
77
|
+
expect((result as { properties: { balance: Record<string, unknown> } }).properties.balance).not.toHaveProperty(
|
|
78
|
+
'type',
|
|
79
|
+
)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('throws a helpful error for non-object input', async () => {
|
|
83
|
+
await expect(valibotToJsonSchema(null)).rejects.toThrow(/expected a Valibot schema but received null/)
|
|
84
|
+
await expect(valibotToJsonSchema(42)).rejects.toThrow(/received number/)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('round-trips through the type generator, including Date fields', async () => {
|
|
88
|
+
const schema = v.object({
|
|
89
|
+
id: v.string(),
|
|
90
|
+
createdAt: v.date(),
|
|
91
|
+
score: v.optional(v.number()),
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
const typeDef = generateTypeDefinition(await valibotToJsonSchema(schema), 'Event')
|
|
95
|
+
|
|
96
|
+
expect(typeDef).toContain('id: string;')
|
|
97
|
+
expect(typeDef).toContain('createdAt: Date;')
|
|
98
|
+
expect(typeDef).toContain('score?: number;')
|
|
99
|
+
})
|
|
100
|
+
})
|