@omnidotdev/odk 0.0.0-stage → 0.1.1
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/README.md +122 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +141 -0
- package/dist/cli.js.map +1 -0
- package/dist/compile.d.ts +152 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +11 -0
- package/dist/compile.js.map +1 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/dist/jsonSchemaExtract.d.ts +40 -0
- package/dist/jsonSchemaExtract.d.ts.map +1 -0
- package/dist/jsonSchemaExtract.js +144 -0
- package/dist/jsonSchemaExtract.js.map +1 -0
- package/dist/odk.d.ts +169 -0
- package/dist/odk.d.ts.map +1 -0
- package/dist/odk.js +186 -0
- package/dist/odk.js.map +1 -0
- package/dist/odk.test.d.ts +2 -0
- package/dist/odk.test.d.ts.map +1 -0
- package/dist/odk.test.js +36 -0
- package/dist/odk.test.js.map +1 -0
- package/dist/standardSchemaAdapter.d.ts +16 -0
- package/dist/standardSchemaAdapter.d.ts.map +1 -0
- package/dist/standardSchemaAdapter.js +277 -0
- package/dist/standardSchemaAdapter.js.map +1 -0
- package/dist/typespecBridge.d.ts +27 -0
- package/dist/typespecBridge.d.ts.map +1 -0
- package/dist/typespecBridge.js +274 -0
- package/dist/typespecBridge.js.map +1 -0
- package/package.json +63 -4
- package/src/cli.ts +160 -0
- package/src/compile.ts +172 -0
- package/src/index.ts +63 -0
- package/src/jsonSchemaExtract.ts +226 -0
- package/src/odk.test.ts +49 -0
- package/src/odk.ts +219 -0
- package/src/standardSchemaAdapter.ts +355 -0
- package/src/typespecBridge.ts +340 -0
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@omnidotdev/odk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Define schemas with Zod/ArkType/Valibot, emit to OpenAPI/Protobuf/etc via TypeSpec",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"odk": "./dist/cli.js"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc",
|
|
19
|
+
"dev": "tsc --watch"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@standard-schema/spec": "^1.0.0",
|
|
23
|
+
"zod-to-json-schema": "^3.24.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"arktype": "^2.1.0",
|
|
27
|
+
"zod": "^4.0.0"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@typespec/compiler": "^1.0.0",
|
|
31
|
+
"@typespec/json-schema": "^1.0.0",
|
|
32
|
+
"@typespec/openapi3": "^1.0.0",
|
|
33
|
+
"@valibot/to-json-schema": "^1.0.0",
|
|
34
|
+
"arktype": "^2.1.0",
|
|
35
|
+
"valibot": "^1.0.0",
|
|
36
|
+
"zod": "^3.24.0 || ^4.0.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"zod": {
|
|
40
|
+
"optional": true
|
|
41
|
+
},
|
|
42
|
+
"arktype": {
|
|
43
|
+
"optional": true
|
|
44
|
+
},
|
|
45
|
+
"valibot": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"@valibot/to-json-schema": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"src"
|
|
55
|
+
],
|
|
56
|
+
"license": "Apache-2.0",
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/omnidotdev/odk.git",
|
|
60
|
+
"directory": "odk-ts"
|
|
61
|
+
},
|
|
62
|
+
"publishConfig": {
|
|
63
|
+
"access": "public"
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// biome-ignore-all lint/suspicious/noConsole: CLI tool — console output is expected
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ODK CLI (TypeScript)
|
|
6
|
+
*
|
|
7
|
+
* Commands:
|
|
8
|
+
* odk compile <schema.ts> Compile and emit schema
|
|
9
|
+
* odk init Initialize a new ODK project
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { writeFile } from "node:fs/promises";
|
|
13
|
+
import { resolve } from "node:path";
|
|
14
|
+
|
|
15
|
+
async function main() {
|
|
16
|
+
const args = process.argv.slice(2);
|
|
17
|
+
const command = args[0];
|
|
18
|
+
|
|
19
|
+
switch (command) {
|
|
20
|
+
case "compile":
|
|
21
|
+
await compileCommand(args.slice(1));
|
|
22
|
+
break;
|
|
23
|
+
case "init":
|
|
24
|
+
await initCommand();
|
|
25
|
+
break;
|
|
26
|
+
case "--help":
|
|
27
|
+
case "-h":
|
|
28
|
+
case undefined:
|
|
29
|
+
printHelp();
|
|
30
|
+
break;
|
|
31
|
+
default:
|
|
32
|
+
console.error(`Unknown command: ${command}`);
|
|
33
|
+
printHelp();
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function printHelp() {
|
|
39
|
+
console.log(`
|
|
40
|
+
ODK - Omni Development Kit
|
|
41
|
+
|
|
42
|
+
Usage:
|
|
43
|
+
odk compile <schema.ts> [options] Compile and emit schema
|
|
44
|
+
odk init Initialize a new ODK project
|
|
45
|
+
odk --help Show this help
|
|
46
|
+
|
|
47
|
+
Compile Options:
|
|
48
|
+
--out, -o <dir> Output directory (default: ./generated)
|
|
49
|
+
--target, -t <name> TypeSpec emitter (can be repeated)
|
|
50
|
+
Examples: @typespec/openapi3, @typespec/json-schema
|
|
51
|
+
|
|
52
|
+
Examples:
|
|
53
|
+
odk compile schema.ts
|
|
54
|
+
odk compile schema.ts -o ./out -t @typespec/openapi3 -t @typespec/json-schema
|
|
55
|
+
odk init
|
|
56
|
+
`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function compileCommand(args: string[]) {
|
|
60
|
+
const schemaArg = args[0];
|
|
61
|
+
if (!schemaArg) {
|
|
62
|
+
console.error("Error: No schema file specified");
|
|
63
|
+
console.error("Usage: odk compile <schema.ts>");
|
|
64
|
+
process.exit(1);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const schemaPath = resolve(schemaArg);
|
|
68
|
+
let outDir = "./generated";
|
|
69
|
+
let targets: string[] = [];
|
|
70
|
+
|
|
71
|
+
// Parse options
|
|
72
|
+
for (let i = 1; i < args.length; i++) {
|
|
73
|
+
if (args[i] === "--out" || args[i] === "-o") {
|
|
74
|
+
outDir = args[++i] ?? outDir;
|
|
75
|
+
} else if (args[i] === "--target" || args[i] === "-t") {
|
|
76
|
+
const target = args[++i];
|
|
77
|
+
if (target) targets.push(target);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (targets.length === 0) {
|
|
82
|
+
targets = ["@typespec/json-schema", "@typespec/openapi3"];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
console.log(`Compiling ${schemaPath}...`);
|
|
86
|
+
console.log(`Targets: ${targets.join(", ")}`);
|
|
87
|
+
console.log(`Output: ${outDir}`);
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
// Dynamic import of the schema file
|
|
91
|
+
const schemaModule = await import(schemaPath);
|
|
92
|
+
|
|
93
|
+
// Look for exported schema (ODKSchema from odk.schema())
|
|
94
|
+
const schema = schemaModule.default || schemaModule.schema;
|
|
95
|
+
|
|
96
|
+
if (!schema) {
|
|
97
|
+
console.error(
|
|
98
|
+
"Error: No schema found. Export a schema as default or named 'schema'.",
|
|
99
|
+
);
|
|
100
|
+
process.exit(1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Import odk and emit
|
|
104
|
+
const { odk } = await import("./odk.js");
|
|
105
|
+
|
|
106
|
+
await odk.emit(schema, {
|
|
107
|
+
targets,
|
|
108
|
+
outDir: resolve(outDir),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
console.log("Done!");
|
|
112
|
+
} catch (error) {
|
|
113
|
+
console.error("Compilation failed:", error);
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function initCommand() {
|
|
119
|
+
console.log("Initializing ODK project...");
|
|
120
|
+
|
|
121
|
+
// Create example schema using modern Zod-based API
|
|
122
|
+
const exampleSchema = `import { odk } from "@omnidotdev/odk";
|
|
123
|
+
import { z } from "zod";
|
|
124
|
+
|
|
125
|
+
// Define your models with Zod
|
|
126
|
+
const UserRole = z.enum(["admin", "user", "guest"]);
|
|
127
|
+
|
|
128
|
+
const User = z.object({
|
|
129
|
+
id: z.string().uuid(),
|
|
130
|
+
email: z.string().email(),
|
|
131
|
+
name: z.string().optional(),
|
|
132
|
+
role: UserRole,
|
|
133
|
+
createdAt: z.string().datetime(),
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
const Post = z.object({
|
|
137
|
+
id: z.string().uuid(),
|
|
138
|
+
title: z.string().min(1).max(200),
|
|
139
|
+
content: z.string(),
|
|
140
|
+
authorId: z.string().uuid(),
|
|
141
|
+
status: z.enum(["draft", "published", "archived"]),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
// Create and export the schema
|
|
145
|
+
export default odk.schema("MyApp", { User, Post, UserRole });
|
|
146
|
+
`;
|
|
147
|
+
|
|
148
|
+
await writeFile("schema.ts", exampleSchema);
|
|
149
|
+
console.log("Created schema.ts");
|
|
150
|
+
|
|
151
|
+
console.log(`
|
|
152
|
+
Next steps:
|
|
153
|
+
1. Install dependencies: bun add zod @omnidotdev/odk
|
|
154
|
+
2. Edit schema.ts to define your models
|
|
155
|
+
3. Run: odk compile schema.ts
|
|
156
|
+
4. Find generated files in ./generated/
|
|
157
|
+
`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
main().catch(console.error);
|
package/src/compile.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CompiledSchema: The intermediate representation (IR) for ODK schemas.
|
|
3
|
+
* This format is consumed by the Rust CLI (tspgen) to emit TypeSpec.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// ============================================================
|
|
7
|
+
// Source Mapping Types
|
|
8
|
+
// ============================================================
|
|
9
|
+
|
|
10
|
+
/** A span in a source file for error mapping. */
|
|
11
|
+
export interface SourceSpan {
|
|
12
|
+
file: string;
|
|
13
|
+
line: number;
|
|
14
|
+
column: number;
|
|
15
|
+
endLine?: number;
|
|
16
|
+
endColumn?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A raw TypeSpec block to pass through verbatim. */
|
|
20
|
+
export interface RawTypeSpecBlock {
|
|
21
|
+
content: string;
|
|
22
|
+
source?: SourceSpan;
|
|
23
|
+
description?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ============================================================
|
|
27
|
+
// Extension Types
|
|
28
|
+
// ============================================================
|
|
29
|
+
|
|
30
|
+
/** Known extension types that ODK understands. */
|
|
31
|
+
type KnownExtension =
|
|
32
|
+
| { kind: "zodTransform"; code: string }
|
|
33
|
+
| { kind: "zodRefinement"; code: string; message?: string }
|
|
34
|
+
| { kind: "decorator"; value: string }
|
|
35
|
+
| { kind: "openApi"; key: string; value: unknown }
|
|
36
|
+
| { kind: "drizzle"; decorator: string; args?: string[] };
|
|
37
|
+
|
|
38
|
+
/** Container for extensions on a field or model. */
|
|
39
|
+
export interface Extensions {
|
|
40
|
+
known?: KnownExtension[];
|
|
41
|
+
[key: string]: unknown; // Unknown extensions pass through
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ============================================================
|
|
45
|
+
// Core Schema Types
|
|
46
|
+
// ============================================================
|
|
47
|
+
|
|
48
|
+
export interface CompiledField {
|
|
49
|
+
name: string;
|
|
50
|
+
type: CompiledType;
|
|
51
|
+
optional?: boolean;
|
|
52
|
+
description?: string;
|
|
53
|
+
constraints?: FieldConstraints;
|
|
54
|
+
/** Decorators and extensions for this field */
|
|
55
|
+
extensions?: Extensions;
|
|
56
|
+
/** Source location for error mapping */
|
|
57
|
+
source?: SourceSpan;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface FieldConstraints {
|
|
61
|
+
minLength?: number;
|
|
62
|
+
maxLength?: number;
|
|
63
|
+
minValue?: number;
|
|
64
|
+
maxValue?: number;
|
|
65
|
+
pattern?: string;
|
|
66
|
+
format?: string;
|
|
67
|
+
multipleOf?: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type CompiledType =
|
|
71
|
+
| { kind: "scalar"; name: ScalarType }
|
|
72
|
+
| { kind: "array"; items: CompiledType }
|
|
73
|
+
| { kind: "ref"; name: string }
|
|
74
|
+
| { kind: "literal"; value: string | number | boolean }
|
|
75
|
+
| { kind: "union"; variants: CompiledType[] }
|
|
76
|
+
| { kind: "object"; fields: CompiledField[] };
|
|
77
|
+
|
|
78
|
+
export type ScalarType =
|
|
79
|
+
| "string"
|
|
80
|
+
| "int32"
|
|
81
|
+
| "int64"
|
|
82
|
+
| "float32"
|
|
83
|
+
| "float64"
|
|
84
|
+
| "boolean"
|
|
85
|
+
| "date"
|
|
86
|
+
| "datetime"
|
|
87
|
+
| "bytes"
|
|
88
|
+
| "unknown";
|
|
89
|
+
|
|
90
|
+
export interface CompiledModel {
|
|
91
|
+
name: string;
|
|
92
|
+
fields: CompiledField[];
|
|
93
|
+
description?: string;
|
|
94
|
+
/** Decorators and extensions for this model */
|
|
95
|
+
extensions?: Extensions;
|
|
96
|
+
/** Source location for error mapping */
|
|
97
|
+
source?: SourceSpan;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface CompiledUnion {
|
|
101
|
+
name: string;
|
|
102
|
+
variants: CompiledUnionVariant[];
|
|
103
|
+
description?: string;
|
|
104
|
+
/** Decorators and extensions for this union */
|
|
105
|
+
extensions?: Extensions;
|
|
106
|
+
/** Source location for error mapping */
|
|
107
|
+
source?: SourceSpan;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface CompiledUnionVariant {
|
|
111
|
+
name: string;
|
|
112
|
+
type?: CompiledType;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The kind of operation. */
|
|
116
|
+
export type OperationKind =
|
|
117
|
+
| "query"
|
|
118
|
+
| "mutation"
|
|
119
|
+
| "subscription"
|
|
120
|
+
| "rpc"
|
|
121
|
+
| "endpoint";
|
|
122
|
+
|
|
123
|
+
/** A compiled operation representing something a client can do. */
|
|
124
|
+
export interface CompiledOperation {
|
|
125
|
+
name: string;
|
|
126
|
+
kind: OperationKind;
|
|
127
|
+
input?: CompiledType;
|
|
128
|
+
output: CompiledType;
|
|
129
|
+
selection?: SelectionSet;
|
|
130
|
+
description?: string;
|
|
131
|
+
extensions?: Extensions;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A set of selected fields within an operation. */
|
|
135
|
+
export interface SelectionSet {
|
|
136
|
+
fields: FieldSelection[];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A single field selection within a selection set. */
|
|
140
|
+
export interface FieldSelection {
|
|
141
|
+
name: string;
|
|
142
|
+
alias?: string;
|
|
143
|
+
arguments?: [string, CompiledType][];
|
|
144
|
+
selection?: SelectionSet;
|
|
145
|
+
directives?: Directive[];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A directive applied to a field selection. */
|
|
149
|
+
export interface Directive {
|
|
150
|
+
name: string;
|
|
151
|
+
arguments?: [string, unknown][];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface CompiledSchema {
|
|
155
|
+
name: string;
|
|
156
|
+
models: CompiledModel[];
|
|
157
|
+
unions: CompiledUnion[];
|
|
158
|
+
/** Operation definitions (queries, mutations, endpoints, RPCs) */
|
|
159
|
+
operations?: CompiledOperation[];
|
|
160
|
+
/** Raw TypeSpec blocks to pass through verbatim */
|
|
161
|
+
rawBlocks?: RawTypeSpecBlock[];
|
|
162
|
+
/** TypeSpec imports required by this schema */
|
|
163
|
+
imports?: string[];
|
|
164
|
+
warnings?: string[];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Serialize a CompiledSchema to JSON for the Rust CLI.
|
|
169
|
+
*/
|
|
170
|
+
export function serializeSchema(schema: CompiledSchema): string {
|
|
171
|
+
return JSON.stringify(schema, null, 2);
|
|
172
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @omnidotdev/odk
|
|
3
|
+
*
|
|
4
|
+
* Define schemas with Zod, ArkType, or Valibot.
|
|
5
|
+
* Emit to OpenAPI, Protobuf, JSON Schema, and more via TypeSpec.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { odk } from "@omnidotdev/odk";
|
|
10
|
+
* import { z } from "zod";
|
|
11
|
+
*
|
|
12
|
+
* const User = z.object({
|
|
13
|
+
* id: z.string().uuid(),
|
|
14
|
+
* email: z.string().email(),
|
|
15
|
+
* role: z.enum(["admin", "user", "guest"]),
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* const schema = odk.schema("MyAPI", { User });
|
|
19
|
+
*
|
|
20
|
+
* // Emit to OpenAPI
|
|
21
|
+
* await odk.emit(schema, {
|
|
22
|
+
* targets: ["@typespec/openapi3"],
|
|
23
|
+
* outDir: "./generated",
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // Or get TypeSpec source
|
|
27
|
+
* const tsp = odk.toTypeSpec(schema);
|
|
28
|
+
*
|
|
29
|
+
* // Or JSON for the Rust CLI
|
|
30
|
+
* const json = odk.toJSON(schema);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
export { serializeSchema } from "./compile.js";
|
|
35
|
+
export { extractJsonSchema, getSchemaLibrary } from "./jsonSchemaExtract.js";
|
|
36
|
+
// Main API
|
|
37
|
+
export { odk } from "./odk.js";
|
|
38
|
+
export { standardSchemaToCompiled } from "./standardSchemaAdapter.js";
|
|
39
|
+
export { compiledSchemaToTypeSpec, emitToTargets } from "./typespecBridge.js";
|
|
40
|
+
|
|
41
|
+
// Core types
|
|
42
|
+
export type {
|
|
43
|
+
CompiledField,
|
|
44
|
+
CompiledModel,
|
|
45
|
+
CompiledOperation,
|
|
46
|
+
CompiledSchema,
|
|
47
|
+
CompiledType,
|
|
48
|
+
CompiledUnion,
|
|
49
|
+
CompiledUnionVariant,
|
|
50
|
+
Directive,
|
|
51
|
+
FieldConstraints,
|
|
52
|
+
FieldSelection,
|
|
53
|
+
OperationKind,
|
|
54
|
+
ScalarType,
|
|
55
|
+
SelectionSet,
|
|
56
|
+
} from "./compile.js";
|
|
57
|
+
// JSON Schema utilities
|
|
58
|
+
export type { JSONSchema } from "./jsonSchemaExtract.js";
|
|
59
|
+
export type { ODKSchema, SchemaOptions } from "./odk.js";
|
|
60
|
+
// Standard Schema adapter
|
|
61
|
+
export type { AdapterOptions } from "./standardSchemaAdapter.js";
|
|
62
|
+
// TypeSpec bridge
|
|
63
|
+
export type { EmitOptions } from "./typespecBridge.js";
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema extraction from different Standard Schema libraries.
|
|
3
|
+
* Each library has its own method for converting to JSON Schema.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
7
|
+
|
|
8
|
+
export interface JSONSchema {
|
|
9
|
+
type?: string | string[];
|
|
10
|
+
properties?: Record<string, JSONSchema>;
|
|
11
|
+
required?: string[];
|
|
12
|
+
items?: JSONSchema;
|
|
13
|
+
enum?: (string | number | boolean)[];
|
|
14
|
+
oneOf?: JSONSchema[];
|
|
15
|
+
anyOf?: JSONSchema[];
|
|
16
|
+
allOf?: JSONSchema[];
|
|
17
|
+
$ref?: string;
|
|
18
|
+
$defs?: Record<string, JSONSchema>;
|
|
19
|
+
definitions?: Record<string, JSONSchema>;
|
|
20
|
+
description?: string;
|
|
21
|
+
title?: string;
|
|
22
|
+
// Constraints
|
|
23
|
+
minLength?: number;
|
|
24
|
+
maxLength?: number;
|
|
25
|
+
minimum?: number;
|
|
26
|
+
maximum?: number;
|
|
27
|
+
exclusiveMinimum?: number;
|
|
28
|
+
exclusiveMaximum?: number;
|
|
29
|
+
pattern?: string;
|
|
30
|
+
format?: string;
|
|
31
|
+
multipleOf?: number;
|
|
32
|
+
// Additional
|
|
33
|
+
additionalProperties?: boolean | JSONSchema;
|
|
34
|
+
default?: unknown;
|
|
35
|
+
const?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Detect which schema library the schema comes from and extract JSON Schema.
|
|
40
|
+
*/
|
|
41
|
+
export function extractJsonSchema(schema: unknown): JSONSchema {
|
|
42
|
+
// Zod detection
|
|
43
|
+
if (isZodSchema(schema)) {
|
|
44
|
+
return extractFromZod(schema);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ArkType detection
|
|
48
|
+
if (isArkTypeSchema(schema)) {
|
|
49
|
+
return extractFromArkType(schema);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Valibot detection
|
|
53
|
+
if (isValibotSchema(schema)) {
|
|
54
|
+
return extractFromValibot(schema);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Check if it's already a Standard Schema with ~standard property
|
|
58
|
+
if (isStandardSchema(schema)) {
|
|
59
|
+
// Try to extract via library-specific methods first
|
|
60
|
+
// Fall back to inferring from the standard schema interface
|
|
61
|
+
return inferFromStandardSchema(schema);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
throw new Error(
|
|
65
|
+
"Unknown schema library. Please use Zod, ArkType, or Valibot.",
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ============ Zod ============
|
|
70
|
+
|
|
71
|
+
// Zod 4 toJSONSchema options
|
|
72
|
+
interface Zod4JsonSchemaOptions {
|
|
73
|
+
unrepresentable?: "any" | "throw";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Zod 4 schema detection (has toJSONSchema method and ~standard.vendor === "zod")
|
|
77
|
+
function isZod4Schema(schema: unknown): schema is {
|
|
78
|
+
toJSONSchema: (opts?: Zod4JsonSchemaOptions) => JSONSchema;
|
|
79
|
+
"~standard": { vendor: string };
|
|
80
|
+
} {
|
|
81
|
+
return (
|
|
82
|
+
schema !== null &&
|
|
83
|
+
typeof schema === "object" &&
|
|
84
|
+
"toJSONSchema" in schema &&
|
|
85
|
+
typeof (schema as Record<string, unknown>).toJSONSchema === "function" &&
|
|
86
|
+
"~standard" in schema &&
|
|
87
|
+
(schema as { "~standard": { vendor: string } })["~standard"]?.vendor ===
|
|
88
|
+
"zod"
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Zod 3 schema detection (has _def property)
|
|
93
|
+
function isZod3Schema(schema: unknown): schema is { _def: unknown } {
|
|
94
|
+
return (
|
|
95
|
+
schema !== null &&
|
|
96
|
+
typeof schema === "object" &&
|
|
97
|
+
"_def" in schema &&
|
|
98
|
+
typeof (schema as Record<string, unknown>)._def === "object" &&
|
|
99
|
+
!("toJSONSchema" in schema) // Not Zod 4
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isZodSchema(schema: unknown): boolean {
|
|
104
|
+
return isZod4Schema(schema) || isZod3Schema(schema);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function extractFromZod(schema: unknown): JSONSchema {
|
|
108
|
+
// Zod 4: Use native toJSONSchema()
|
|
109
|
+
if (isZod4Schema(schema)) {
|
|
110
|
+
// Use unrepresentable: 'any' to avoid throwing on Date, Function, etc.
|
|
111
|
+
// These will become empty schemas {} which we handle gracefully
|
|
112
|
+
return schema.toJSONSchema({ unrepresentable: "any" }) as JSONSchema;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Zod 3: Use zod-to-json-schema library
|
|
116
|
+
if (isZod3Schema(schema)) {
|
|
117
|
+
try {
|
|
118
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
119
|
+
const { zodToJsonSchema } = require("zod-to-json-schema");
|
|
120
|
+
return zodToJsonSchema(schema, { $refStrategy: "none" }) as JSONSchema;
|
|
121
|
+
} catch {
|
|
122
|
+
throw new Error(
|
|
123
|
+
"zod-to-json-schema is required for Zod 3 schemas. Install it with: bun add zod-to-json-schema",
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
throw new Error("Unknown Zod schema version");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ============ ArkType ============
|
|
132
|
+
|
|
133
|
+
function isArkTypeSchema(schema: unknown): boolean {
|
|
134
|
+
// ArkType schemas are functions (callable validators), not plain objects
|
|
135
|
+
if (
|
|
136
|
+
schema === null ||
|
|
137
|
+
(typeof schema !== "object" && typeof schema !== "function")
|
|
138
|
+
)
|
|
139
|
+
return false;
|
|
140
|
+
|
|
141
|
+
// Check for ~standard.vendor === "arktype"
|
|
142
|
+
if (
|
|
143
|
+
"~standard" in schema &&
|
|
144
|
+
(schema as { "~standard": { vendor: string } })["~standard"]?.vendor ===
|
|
145
|
+
"arktype"
|
|
146
|
+
) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Fallback: check for toJsonSchema method (lowercase, on prototype)
|
|
151
|
+
return (
|
|
152
|
+
typeof (schema as { toJsonSchema?: unknown }).toJsonSchema === "function"
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function extractFromArkType(schema: unknown): JSONSchema {
|
|
157
|
+
const s = schema as { toJsonSchema: () => JSONSchema };
|
|
158
|
+
return s.toJsonSchema();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ============ Valibot ============
|
|
162
|
+
|
|
163
|
+
function isValibotSchema(
|
|
164
|
+
schema: unknown,
|
|
165
|
+
): schema is { kind: string; type: string } {
|
|
166
|
+
return (
|
|
167
|
+
schema !== null &&
|
|
168
|
+
typeof schema === "object" &&
|
|
169
|
+
"kind" in schema &&
|
|
170
|
+
(schema as Record<string, unknown>).kind === "schema"
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function extractFromValibot(schema: unknown): JSONSchema {
|
|
175
|
+
try {
|
|
176
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
177
|
+
const { toJsonSchema } = require("@valibot/to-json-schema");
|
|
178
|
+
return toJsonSchema(schema) as JSONSchema;
|
|
179
|
+
} catch {
|
|
180
|
+
throw new Error(
|
|
181
|
+
"@valibot/to-json-schema is required for Valibot schemas. Install it with: bun add @valibot/to-json-schema",
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ============ Standard Schema Fallback ============
|
|
187
|
+
|
|
188
|
+
function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {
|
|
189
|
+
return (
|
|
190
|
+
schema !== null &&
|
|
191
|
+
typeof schema === "object" &&
|
|
192
|
+
"~standard" in schema &&
|
|
193
|
+
typeof (schema as Record<string, unknown>)["~standard"] === "object"
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function inferFromStandardSchema(schema: StandardSchemaV1): JSONSchema {
|
|
198
|
+
// Standard Schema spec doesn't mandate JSON Schema output,
|
|
199
|
+
// so we can only infer basic structure from the types property
|
|
200
|
+
const standard = schema["~standard"];
|
|
201
|
+
|
|
202
|
+
// If the schema library provides vendor-specific JSON Schema, use it
|
|
203
|
+
if ("toJsonSchema" in schema && typeof schema.toJsonSchema === "function") {
|
|
204
|
+
return (schema as { toJsonSchema: () => JSONSchema }).toJsonSchema();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Otherwise, return a minimal schema with unknown type
|
|
208
|
+
// The adapter will warn about this
|
|
209
|
+
return {
|
|
210
|
+
type: "object",
|
|
211
|
+
description: `Standard Schema (vendor: ${standard.vendor})`,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Get the library name from a schema for error messages.
|
|
217
|
+
*/
|
|
218
|
+
export function getSchemaLibrary(schema: unknown): string {
|
|
219
|
+
if (isZod4Schema(schema) || isZod3Schema(schema)) return "zod";
|
|
220
|
+
if (isArkTypeSchema(schema)) return "arktype";
|
|
221
|
+
if (isValibotSchema(schema)) return "valibot";
|
|
222
|
+
if (isStandardSchema(schema)) {
|
|
223
|
+
return (schema as StandardSchemaV1)["~standard"].vendor;
|
|
224
|
+
}
|
|
225
|
+
return "unknown";
|
|
226
|
+
}
|