@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.
@@ -0,0 +1,77 @@
1
+ import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension'
2
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
3
+
4
+ // Minimal structural view of `@valibot/to-json-schema`, so the adapter does not
5
+ // hard-depend on its types — the converter is loaded at runtime as an optional
6
+ // peer dependency.
7
+ type ValibotOverrideContext = { readonly valibotSchema?: { readonly type?: string } }
8
+
9
+ type ValibotConfig = {
10
+ readonly errorMode?: 'throw' | 'warn' | 'ignore'
11
+ readonly overrideSchema?: (ctx: ValibotOverrideContext) => Record<string, unknown> | undefined
12
+ }
13
+
14
+ type ToJsonSchema = (schema: unknown, config?: ValibotConfig) => Record<string, unknown>
15
+
16
+ /**
17
+ * Resolves `@valibot/to-json-schema`'s `toJsonSchema` from a runtime import,
18
+ * throwing a clear error when the converter is missing.
19
+ */
20
+ const loadToJsonSchema = async (): Promise<ToJsonSchema> => {
21
+ let mod: Record<string, unknown>
22
+ try {
23
+ mod = (await import('@valibot/to-json-schema')) as Record<string, unknown>
24
+ } catch {
25
+ throw new Error(
26
+ "The Valibot adapter requires '@valibot/to-json-schema' (and 'valibot') to be installed in your project.",
27
+ )
28
+ }
29
+
30
+ const named = mod['toJsonSchema']
31
+ const fromDefault = (mod['default'] as Record<string, unknown> | undefined)?.['toJsonSchema']
32
+ const converter = typeof named === 'function' ? named : typeof fromDefault === 'function' ? fromDefault : undefined
33
+
34
+ if (!converter) {
35
+ throw new Error("'@valibot/to-json-schema' did not export 'toJsonSchema'.")
36
+ }
37
+
38
+ return converter as ToJsonSchema
39
+ }
40
+
41
+ /**
42
+ * Converts a Valibot schema into a Draft 2020-12 JSON Schema via
43
+ * `@valibot/to-json-schema`.
44
+ *
45
+ * Valibot's `date` schema has no JSON Schema representation and would otherwise
46
+ * throw, so we run with `errorMode: 'ignore'` (other unsupported constructs
47
+ * degrade to an open schema rather than failing the whole conversion) and use
48
+ * the `overrideSchema` hook to rewrite dates into the shared `x-mjst` instanceOf
49
+ * extension — the same handling TypeBox and Zod dates receive.
50
+ */
51
+ export const valibotToJsonSchema = async (source: unknown): Promise<JSONSchema> => {
52
+ if (typeof source !== 'object' || source === null) {
53
+ const received = source === null ? 'null' : typeof source
54
+ throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`)
55
+ }
56
+
57
+ const toJsonSchema = await loadToJsonSchema()
58
+
59
+ let json: Record<string, unknown>
60
+ try {
61
+ json = toJsonSchema(source, {
62
+ errorMode: 'ignore',
63
+ overrideSchema: (ctx) => {
64
+ if (ctx.valibotSchema?.type === 'date') return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } }
65
+ if (ctx.valibotSchema?.type === 'bigint') return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } }
66
+ return undefined
67
+ },
68
+ })
69
+ } catch (error) {
70
+ throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`)
71
+ }
72
+
73
+ // Valibot emits a draft-07 dialect marker; the generators target 2020-12.
74
+ delete json['$schema']
75
+
76
+ return json as JSONSchema
77
+ }
@@ -0,0 +1,114 @@
1
+ import { generateTypeDefinition } from '@amritk/helpers/generate-type-definition'
2
+ import { describe, expect, it } from 'vitest'
3
+ import * as zodModule from 'zod'
4
+
5
+ import { zodToJsonSchema } from './zod-to-json-schema'
6
+
7
+ // Resolve the `z` namespace regardless of how the installed Zod build exports it.
8
+ const z = ((zodModule as Record<string, unknown>)['z'] ??
9
+ (zodModule as Record<string, unknown>)['default'] ??
10
+ zodModule) as typeof import('zod')['z']
11
+
12
+ describe('zodToJsonSchema', () => {
13
+ it('converts a flat object with required and optional fields', async () => {
14
+ const schema = z.object({
15
+ name: z.string(),
16
+ age: z.number().int().optional(),
17
+ score: z.number().optional(),
18
+ })
19
+
20
+ const result = await zodToJsonSchema(schema)
21
+
22
+ expect(result).toMatchObject({
23
+ type: 'object',
24
+ properties: {
25
+ name: { type: 'string' },
26
+ age: { type: 'integer' },
27
+ score: { type: 'number' },
28
+ },
29
+ required: ['name'],
30
+ })
31
+ expect((result as { required: string[] }).required).not.toContain('age')
32
+ expect((result as { required: string[] }).required).not.toContain('score')
33
+ })
34
+
35
+ it('strips the $schema dialect marker', async () => {
36
+ const result = await zodToJsonSchema(z.object({ name: z.string() }))
37
+ expect(result).not.toHaveProperty('$schema')
38
+ })
39
+
40
+ it('converts enums to a string schema with an enum list', async () => {
41
+ const result = await zodToJsonSchema(z.object({ role: z.enum(['admin', 'user']) }))
42
+
43
+ expect(result).toMatchObject({
44
+ properties: { role: { type: 'string', enum: ['admin', 'user'] } },
45
+ })
46
+ })
47
+
48
+ it('converts arrays and nested objects', async () => {
49
+ const schema = z.object({
50
+ tags: z.array(z.string()),
51
+ profile: z.object({ id: z.string() }),
52
+ })
53
+
54
+ const result = await zodToJsonSchema(schema)
55
+
56
+ expect(result).toMatchObject({
57
+ properties: {
58
+ tags: { type: 'array', items: { type: 'string' } },
59
+ profile: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
60
+ },
61
+ })
62
+ })
63
+
64
+ it('converts a top-level scalar schema', async () => {
65
+ expect(await zodToJsonSchema(z.string())).toMatchObject({ type: 'string' })
66
+ })
67
+
68
+ it('maps z.date() to an x-mjst instanceOf Date hint', async () => {
69
+ const result = await zodToJsonSchema(z.object({ when: z.date(), name: z.string() }))
70
+
71
+ expect(result).toMatchObject({
72
+ properties: {
73
+ when: { 'x-mjst': { instanceOf: 'Date' } },
74
+ name: { type: 'string' },
75
+ },
76
+ })
77
+ // The date property must not carry a leftover JSON Schema `type`.
78
+ expect((result as { properties: { when: Record<string, unknown> } }).properties.when).not.toHaveProperty('type')
79
+ })
80
+
81
+ it('maps z.bigint() to an x-mjst primitive bigint hint', async () => {
82
+ const result = await zodToJsonSchema(z.object({ balance: z.bigint(), name: z.string() }))
83
+
84
+ expect(result).toMatchObject({
85
+ properties: {
86
+ balance: { 'x-mjst': { primitive: 'bigint' } },
87
+ name: { type: 'string' },
88
+ },
89
+ })
90
+ expect((result as { properties: { balance: Record<string, unknown> } }).properties.balance).not.toHaveProperty(
91
+ 'type',
92
+ )
93
+ })
94
+
95
+ it('throws a helpful error for non-object input', async () => {
96
+ await expect(zodToJsonSchema(null)).rejects.toThrow(/expected a Zod schema but received null/)
97
+ await expect(zodToJsonSchema('nope')).rejects.toThrow(/received string/)
98
+ })
99
+
100
+ it('round-trips through the type generator, including Date fields', async () => {
101
+ const schema = z.object({
102
+ id: z.string(),
103
+ createdAt: z.date(),
104
+ score: z.number().optional(),
105
+ })
106
+
107
+ const json = await zodToJsonSchema(schema)
108
+ const typeDef = generateTypeDefinition(json, 'Event')
109
+
110
+ expect(typeDef).toContain('id: string;')
111
+ expect(typeDef).toContain('createdAt: Date;')
112
+ expect(typeDef).toContain('score?: number;')
113
+ })
114
+ })
@@ -0,0 +1,87 @@
1
+ import { MJST_EXTENSION_KEY } from '@amritk/helpers/mjst-extension'
2
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
3
+
4
+ // Zod 4's `toJSONSchema` does the heavy lifting. We only describe the slice of
5
+ // its surface we touch so the adapter does not need a hard dependency on Zod's
6
+ // types — `zod` stays an optional peer dependency loaded at runtime.
7
+ type ToJsonSchema = (schema: unknown, options?: ZodToJsonSchemaOptions) => Record<string, unknown>
8
+
9
+ type OverrideContext = {
10
+ readonly zodSchema?: { readonly _zod?: { readonly def?: { readonly type?: string } } }
11
+ readonly jsonSchema: Record<string, unknown>
12
+ }
13
+
14
+ type ZodToJsonSchemaOptions = {
15
+ readonly unrepresentable?: 'any' | 'throw'
16
+ readonly override?: (ctx: OverrideContext) => void
17
+ }
18
+
19
+ /**
20
+ * Resolves Zod's `toJSONSchema` from a runtime import, tolerating both the
21
+ * named export (`import { toJSONSchema }`) and the `z` namespace
22
+ * (`z.toJSONSchema`). Throws a clear error when Zod is missing or too old,
23
+ * since `toJSONSchema` only exists in Zod 4 and later.
24
+ */
25
+ const loadToJsonSchema = async (): Promise<ToJsonSchema> => {
26
+ let mod: Record<string, unknown>
27
+ try {
28
+ mod = (await import('zod')) as Record<string, unknown>
29
+ } catch {
30
+ throw new Error("The Zod adapter requires 'zod' (v4 or later) to be installed in your project.")
31
+ }
32
+
33
+ const named = mod['toJSONSchema']
34
+ const namespace = (mod['z'] ?? mod['default'] ?? mod) as Record<string, unknown> | undefined
35
+ const fromNamespace = namespace?.['toJSONSchema']
36
+ const converter =
37
+ typeof named === 'function' ? named : typeof fromNamespace === 'function' ? fromNamespace : undefined
38
+
39
+ if (!converter) {
40
+ throw new Error("Zod's 'toJSONSchema' was not found. The Zod adapter requires zod v4 or later.")
41
+ }
42
+
43
+ return converter as ToJsonSchema
44
+ }
45
+
46
+ /**
47
+ * Converts a Zod schema into a Draft 2020-12 JSON Schema using Zod 4's native
48
+ * `toJSONSchema`.
49
+ *
50
+ * Zod's `z.date()` has no JSON Schema representation and would otherwise throw.
51
+ * We pass `unrepresentable: 'any'` so conversion never fails on it, then use the
52
+ * `override` hook to rewrite date schemas into an `x-mjst` instanceOf hint — the
53
+ * same extension TypeBox dates use — so generated types and runtime checks treat
54
+ * them as `Date`.
55
+ */
56
+ export const zodToJsonSchema = async (source: unknown): Promise<JSONSchema> => {
57
+ if (typeof source !== 'object' || source === null) {
58
+ const received = source === null ? 'null' : typeof source
59
+ throw new Error(`Zod adapter expected a Zod schema but received ${received}.`)
60
+ }
61
+
62
+ const toJSONSchema = await loadToJsonSchema()
63
+
64
+ let json: Record<string, unknown>
65
+ try {
66
+ json = toJSONSchema(source, {
67
+ unrepresentable: 'any',
68
+ override: (ctx) => {
69
+ const type = ctx.zodSchema?._zod?.def?.type
70
+ if (type === 'date') {
71
+ for (const key of Object.keys(ctx.jsonSchema)) delete ctx.jsonSchema[key]
72
+ ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: 'Date' }
73
+ } else if (type === 'bigint') {
74
+ for (const key of Object.keys(ctx.jsonSchema)) delete ctx.jsonSchema[key]
75
+ ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: 'bigint' }
76
+ }
77
+ },
78
+ })
79
+ } catch (error) {
80
+ throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`)
81
+ }
82
+
83
+ // The dialect marker is noise for the generators, which already target 2020-12.
84
+ delete json['$schema']
85
+
86
+ return json as JSONSchema
87
+ }