@amritk/adapters 0.2.8 → 0.2.10

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 CHANGED
@@ -20,4 +20,3 @@ export type Adapter = {
20
20
  */
21
21
  readonly toJSONSchema: (source: unknown) => JSONSchema | Promise<JSONSchema>;
22
22
  };
23
- //# sourceMappingURL=adapter.d.ts.map
@@ -9,4 +9,3 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
9
9
  * expects on the wire — only stripping the dialect marker.
10
10
  */
11
11
  export declare const effectToJsonSchema: (source: unknown) => Promise<JSONSchema>;
12
- //# sourceMappingURL=effect-to-json-schema.d.ts.map
@@ -9,4 +9,3 @@ import type { SourceFormat } from './source-format.js';
9
9
  * so the CLI can fail fast with guidance instead of a cryptic crash.
10
10
  */
11
11
  export declare const getAdapter: (format: SourceFormat) => Adapter;
12
- //# sourceMappingURL=get-adapter.d.ts.map
@@ -9,4 +9,3 @@
9
9
  * source of truth for what is actually implemented today.
10
10
  */
11
11
  export type SourceFormat = 'json' | 'typebox' | 'zod' | 'valibot' | 'effect';
12
- //# sourceMappingURL=source-format.d.ts.map
@@ -11,4 +11,3 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
11
11
  * by the consumer's schema module, never by mjst itself.
12
12
  */
13
13
  export declare const typeboxToJsonSchema: (source: unknown) => JSONSchema;
14
- //# sourceMappingURL=typebox-to-json-schema.d.ts.map
@@ -11,4 +11,3 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
11
11
  * extension — the same handling TypeBox and Zod dates receive.
12
12
  */
13
13
  export declare const valibotToJsonSchema: (source: unknown) => Promise<JSONSchema>;
14
- //# sourceMappingURL=valibot-to-json-schema.d.ts.map
@@ -10,4 +10,3 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
10
10
  * them as `Date`.
11
11
  */
12
12
  export declare const zodToJsonSchema: (source: unknown) => Promise<JSONSchema>;
13
- //# sourceMappingURL=zod-to-json-schema.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/adapters",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "Convert schemas from external libraries (TypeBox, Zod, ...) into JSON Schema for mjst.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,8 +25,7 @@
25
25
  "url": "https://github.com/amritk/mjst/issues"
26
26
  },
27
27
  "files": [
28
- "dist",
29
- "src"
28
+ "dist"
30
29
  ],
31
30
  "publishConfig": {
32
31
  "access": "public"
@@ -38,42 +37,35 @@
38
37
  },
39
38
  "dependencies": {
40
39
  "json-schema-typed": "^8.0.1",
41
- "@amritk/helpers": "0.8.0"
40
+ "@amritk/helpers": "0.10.0"
42
41
  },
43
42
  "exports": {
44
43
  "./package.json": "./package.json",
45
44
  "./adapter": {
46
- "development": "./src/adapter.ts",
47
45
  "default": "./dist/adapter.js",
48
46
  "types": "./dist/adapter.d.ts"
49
47
  },
50
48
  "./source-format": {
51
- "development": "./src/source-format.ts",
52
49
  "default": "./dist/source-format.js",
53
50
  "types": "./dist/source-format.d.ts"
54
51
  },
55
52
  "./get-adapter": {
56
- "development": "./src/get-adapter.ts",
57
53
  "default": "./dist/get-adapter.js",
58
54
  "types": "./dist/get-adapter.d.ts"
59
55
  },
60
56
  "./typebox-to-json-schema": {
61
- "development": "./src/typebox-to-json-schema.ts",
62
57
  "default": "./dist/typebox-to-json-schema.js",
63
58
  "types": "./dist/typebox-to-json-schema.d.ts"
64
59
  },
65
60
  "./zod-to-json-schema": {
66
- "development": "./src/zod-to-json-schema.ts",
67
61
  "default": "./dist/zod-to-json-schema.js",
68
62
  "types": "./dist/zod-to-json-schema.d.ts"
69
63
  },
70
64
  "./valibot-to-json-schema": {
71
- "development": "./src/valibot-to-json-schema.ts",
72
65
  "default": "./dist/valibot-to-json-schema.js",
73
66
  "types": "./dist/valibot-to-json-schema.d.ts"
74
67
  },
75
68
  "./effect-to-json-schema": {
76
- "development": "./src/effect-to-json-schema.ts",
77
69
  "default": "./dist/effect-to-json-schema.js",
78
70
  "types": "./dist/effect-to-json-schema.d.ts"
79
71
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AAEjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAEnD;;;;;;;;;GASG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAA;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAA;CAC7E,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"effect-to-json-schema.d.ts","sourceRoot":"","sources":["../src/effect-to-json-schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AA4BjE;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,WAAkB,OAAO,KAAG,OAAO,CAAC,UAAU,CAmB5E,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"get-adapter.d.ts","sourceRoot":"","sources":["../src/get-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAyBnD;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,WAAY,YAAY,KAAG,OAgBjD,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"source-format.d.ts","sourceRoot":"","sources":["../src/source-format.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,GAAG,SAAS,GAAG,QAAQ,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"typebox-to-json-schema.d.ts","sourceRoot":"","sources":["../src/typebox-to-json-schema.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AAwDjE;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,WAAY,OAAO,KAAG,UAUrD,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"valibot-to-json-schema.d.ts","sourceRoot":"","sources":["../src/valibot-to-json-schema.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AAuCjE;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,WAAkB,OAAO,KAAG,OAAO,CAAC,UAAU,CA0B7E,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"zod-to-json-schema.d.ts","sourceRoot":"","sources":["../src/zod-to-json-schema.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAA;AA4CjE;;;;;;;;;GASG;AACH,eAAO,MAAM,eAAe,WAAkB,OAAO,KAAG,OAAO,CAAC,UAAU,CA6CzE,CAAA"}
package/src/adapter.ts DELETED
@@ -1,24 +0,0 @@
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
- }
@@ -1,74 +0,0 @@
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
- })
@@ -1,57 +0,0 @@
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
- }
@@ -1,36 +0,0 @@
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
- })
@@ -1,52 +0,0 @@
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
- }
@@ -1,11 +0,0 @@
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'
@@ -1,121 +0,0 @@
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
- })
@@ -1,79 +0,0 @@
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
- }
@@ -1,100 +0,0 @@
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
- })
@@ -1,78 +0,0 @@
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: 'warn'` (other unsupported constructs degrade
47
- * to an open schema rather than failing the whole conversion, and the converter
48
- * logs which ones — so the widening is visible instead of silent) and use the
49
- * `overrideSchema` hook to rewrite dates into the shared `x-mjst` instanceOf
50
- * extension — the same handling TypeBox and Zod dates receive.
51
- */
52
- export const valibotToJsonSchema = async (source: unknown): Promise<JSONSchema> => {
53
- if (typeof source !== 'object' || source === null) {
54
- const received = source === null ? 'null' : typeof source
55
- throw new Error(`Valibot adapter expected a Valibot schema but received ${received}.`)
56
- }
57
-
58
- const toJsonSchema = await loadToJsonSchema()
59
-
60
- let json: Record<string, unknown>
61
- try {
62
- json = toJsonSchema(source, {
63
- errorMode: 'warn',
64
- overrideSchema: (ctx) => {
65
- if (ctx.valibotSchema?.type === 'date') return { [MJST_EXTENSION_KEY]: { instanceOf: 'Date' } }
66
- if (ctx.valibotSchema?.type === 'bigint') return { [MJST_EXTENSION_KEY]: { primitive: 'bigint' } }
67
- return undefined
68
- },
69
- })
70
- } catch (error) {
71
- throw new Error(`Valibot adapter failed to convert the schema. Is it a valid Valibot schema?\n${String(error)}`)
72
- }
73
-
74
- // Valibot emits a draft-07 dialect marker; the generators target 2020-12.
75
- delete json['$schema']
76
-
77
- return json as JSONSchema
78
- }
@@ -1,124 +0,0 @@
1
- import { generateTypeDefinition } from '@amritk/helpers/generate-type-definition'
2
- import { describe, expect, it, vi } 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('warns when a lossy (unrepresentable) Zod type is widened to "accept anything"', async () => {
41
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
42
- try {
43
- await zodToJsonSchema(z.object({ id: z.string(), sym: z.symbol() }))
44
- expect(warn).toHaveBeenCalledWith(expect.stringMatching(/Zod adapter: symbol/))
45
- } finally {
46
- warn.mockRestore()
47
- }
48
- })
49
-
50
- it('converts enums to a string schema with an enum list', async () => {
51
- const result = await zodToJsonSchema(z.object({ role: z.enum(['admin', 'user']) }))
52
-
53
- expect(result).toMatchObject({
54
- properties: { role: { type: 'string', enum: ['admin', 'user'] } },
55
- })
56
- })
57
-
58
- it('converts arrays and nested objects', async () => {
59
- const schema = z.object({
60
- tags: z.array(z.string()),
61
- profile: z.object({ id: z.string() }),
62
- })
63
-
64
- const result = await zodToJsonSchema(schema)
65
-
66
- expect(result).toMatchObject({
67
- properties: {
68
- tags: { type: 'array', items: { type: 'string' } },
69
- profile: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
70
- },
71
- })
72
- })
73
-
74
- it('converts a top-level scalar schema', async () => {
75
- expect(await zodToJsonSchema(z.string())).toMatchObject({ type: 'string' })
76
- })
77
-
78
- it('maps z.date() to an x-mjst instanceOf Date hint', async () => {
79
- const result = await zodToJsonSchema(z.object({ when: z.date(), name: z.string() }))
80
-
81
- expect(result).toMatchObject({
82
- properties: {
83
- when: { 'x-mjst': { instanceOf: 'Date' } },
84
- name: { type: 'string' },
85
- },
86
- })
87
- // The date property must not carry a leftover JSON Schema `type`.
88
- expect((result as { properties: { when: Record<string, unknown> } }).properties.when).not.toHaveProperty('type')
89
- })
90
-
91
- it('maps z.bigint() to an x-mjst primitive bigint hint', async () => {
92
- const result = await zodToJsonSchema(z.object({ balance: z.bigint(), name: z.string() }))
93
-
94
- expect(result).toMatchObject({
95
- properties: {
96
- balance: { 'x-mjst': { primitive: 'bigint' } },
97
- name: { type: 'string' },
98
- },
99
- })
100
- expect((result as { properties: { balance: Record<string, unknown> } }).properties.balance).not.toHaveProperty(
101
- 'type',
102
- )
103
- })
104
-
105
- it('throws a helpful error for non-object input', async () => {
106
- await expect(zodToJsonSchema(null)).rejects.toThrow(/expected a Zod schema but received null/)
107
- await expect(zodToJsonSchema('nope')).rejects.toThrow(/received string/)
108
- })
109
-
110
- it('round-trips through the type generator, including Date fields', async () => {
111
- const schema = z.object({
112
- id: z.string(),
113
- createdAt: z.date(),
114
- score: z.number().optional(),
115
- })
116
-
117
- const json = await zodToJsonSchema(schema)
118
- const typeDef = generateTypeDefinition(json, 'Event')
119
-
120
- expect(typeDef).toContain('id: string;')
121
- expect(typeDef).toContain('createdAt: Date;')
122
- expect(typeDef).toContain('score?: number;')
123
- })
124
- })
@@ -1,101 +0,0 @@
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
- // Zod types with no JSON Schema equivalent that we do *not* rescue into an
65
- // `x-mjst` hint. `unrepresentable: 'any'` turns these into `{}` (accepts
66
- // anything), which silently widens the generated type — so we surface them.
67
- const LOSSY_TYPES = new Set(['symbol', 'nan', 'void', 'undefined', 'never', 'map', 'set', 'promise', 'function'])
68
- const droppedTypes = new Set<string>()
69
-
70
- let json: Record<string, unknown>
71
- try {
72
- json = toJSONSchema(source, {
73
- unrepresentable: 'any',
74
- override: (ctx) => {
75
- const type = ctx.zodSchema?._zod?.def?.type
76
- if (type === 'date') {
77
- for (const key of Object.keys(ctx.jsonSchema)) delete ctx.jsonSchema[key]
78
- ctx.jsonSchema[MJST_EXTENSION_KEY] = { instanceOf: 'Date' }
79
- } else if (type === 'bigint') {
80
- for (const key of Object.keys(ctx.jsonSchema)) delete ctx.jsonSchema[key]
81
- ctx.jsonSchema[MJST_EXTENSION_KEY] = { primitive: 'bigint' }
82
- } else if (type && LOSSY_TYPES.has(type)) {
83
- droppedTypes.add(type)
84
- }
85
- },
86
- })
87
- } catch (error) {
88
- throw new Error(`Zod adapter failed to convert the schema. Is it a valid Zod schema?\n${String(error)}`)
89
- }
90
-
91
- if (droppedTypes.size > 0) {
92
- console.warn(
93
- `[mjst] Zod adapter: ${[...droppedTypes].sort().join(', ')} ${droppedTypes.size === 1 ? 'has' : 'have'} no JSON Schema representation and became "accept anything". The generated type will be wider than the Zod schema.`,
94
- )
95
- }
96
-
97
- // The dialect marker is noise for the generators, which already target 2020-12.
98
- delete json['$schema']
99
-
100
- return json as JSONSchema
101
- }