@omnidotdev/odk 0.0.0-stage → 0.1.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/src/odk.ts ADDED
@@ -0,0 +1,223 @@
1
+ /**
2
+ * ODK - Omni Development Kit
3
+ *
4
+ * Main API for defining schemas and emitting to various targets.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { odk } from "@omnidotdev/odk";
9
+ * import { z } from "zod";
10
+ *
11
+ * const User = z.object({
12
+ * id: z.string().uuid(),
13
+ * email: z.string().email(),
14
+ * name: z.string().optional(),
15
+ * });
16
+ *
17
+ * const schema = odk.schema("MyAPI", { User });
18
+ *
19
+ * await odk.emit(schema, {
20
+ * targets: ["@typespec/openapi3"],
21
+ * outDir: "./generated",
22
+ * });
23
+ * ```
24
+ *
25
+ * @example Escape hatches for advanced use cases
26
+ * ```typescript
27
+ * // Add raw TypeSpec code
28
+ * const schema = odk.schema("MyAPI", { User });
29
+ * odk.raw(schema, `
30
+ * @route("/api")
31
+ * interface CustomApi {
32
+ * @get op health(): void;
33
+ * }
34
+ * `);
35
+ *
36
+ * // Add custom imports
37
+ * odk.addImport(schema, "@typespec/http");
38
+ * ```
39
+ */
40
+
41
+ import type { CompiledSchema, RawTypeSpecBlock } from "./compile.js";
42
+ import {
43
+ standardSchemaToCompiled,
44
+ type AdapterOptions,
45
+ } from "./standardSchemaAdapter.js";
46
+ import {
47
+ emitToTargets,
48
+ compiledSchemaToTypeSpec,
49
+ type EmitOptions,
50
+ } from "./typespecBridge.js";
51
+
52
+ export interface SchemaOptions extends AdapterOptions {
53
+ /** Description for the schema namespace */
54
+ description?: string;
55
+ /** TypeSpec imports to include */
56
+ imports?: string[];
57
+ }
58
+
59
+ export interface ODKSchema {
60
+ /** The compiled schema representation */
61
+ compiled: CompiledSchema;
62
+ /** The original types passed to schema() */
63
+ types: Record<string, unknown>;
64
+ }
65
+
66
+ /**
67
+ * Create an ODK schema from Standard Schema-compliant types.
68
+ *
69
+ * @param name - Name for the schema namespace
70
+ * @param types - Record of named types (Zod, ArkType, or Valibot schemas)
71
+ * @param options - Optional configuration
72
+ * @returns ODK schema object
73
+ *
74
+ * @example
75
+ * ```typescript
76
+ * const User = z.object({ id: z.string(), name: z.string() });
77
+ * const Post = z.object({ title: z.string(), authorId: z.string() });
78
+ *
79
+ * const schema = odk.schema("Blog", { User, Post });
80
+ * ```
81
+ */
82
+ function schema(
83
+ name: string,
84
+ types: Record<string, unknown>,
85
+ options: SchemaOptions = {},
86
+ ): ODKSchema {
87
+ const compiled = standardSchemaToCompiled(name, types, options);
88
+
89
+ // Add imports from options
90
+ if (options.imports) {
91
+ compiled.imports = [...(compiled.imports ?? []), ...options.imports];
92
+ }
93
+
94
+ return { compiled, types };
95
+ }
96
+
97
+ /**
98
+ * Add a raw TypeSpec block to the schema.
99
+ *
100
+ * Use this escape hatch when you need to write TypeSpec code that
101
+ * ODK's schema API doesn't support.
102
+ *
103
+ * @param schema - ODK schema to modify
104
+ * @param content - Raw TypeSpec code
105
+ * @param description - Optional description/comment
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * odk.raw(schema, `
110
+ * @route("/api")
111
+ * interface CustomApi {
112
+ * @get op health(): void;
113
+ * }
114
+ * `);
115
+ * ```
116
+ */
117
+ function raw(schema: ODKSchema, content: string, description?: string): void {
118
+ const block: RawTypeSpecBlock = { content };
119
+ if (description) {
120
+ block.description = description;
121
+ }
122
+
123
+ if (!schema.compiled.rawBlocks) {
124
+ schema.compiled.rawBlocks = [];
125
+ }
126
+ schema.compiled.rawBlocks.push(block);
127
+ }
128
+
129
+ /**
130
+ * Add a TypeSpec import to the schema.
131
+ *
132
+ * @param schema - ODK schema to modify
133
+ * @param importPath - Import path (e.g., "@typespec/http")
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * odk.addImport(schema, "@typespec/http");
138
+ * odk.addImport(schema, "@omnidotdev/typespec-drizzle");
139
+ * ```
140
+ */
141
+ function addImport(schema: ODKSchema, importPath: string): void {
142
+ if (!schema.compiled.imports) {
143
+ schema.compiled.imports = [];
144
+ }
145
+ if (!schema.compiled.imports.includes(importPath)) {
146
+ schema.compiled.imports.push(importPath);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Emit an ODK schema to target formats.
152
+ *
153
+ * @param schema - ODK schema created with odk.schema()
154
+ * @param options - Emission options (targets, output directory)
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * await odk.emit(schema, {
159
+ * targets: ["@typespec/openapi3", "@typespec/protobuf"],
160
+ * outDir: "./generated",
161
+ * });
162
+ * ```
163
+ */
164
+ async function emit(schema: ODKSchema, options: EmitOptions): Promise<void> {
165
+ await emitToTargets(schema.compiled, options);
166
+ }
167
+
168
+ /**
169
+ * Generate TypeSpec source code from an ODK schema.
170
+ *
171
+ * @param schema - ODK schema created with odk.schema()
172
+ * @param namespace - Optional namespace override
173
+ * @returns TypeSpec source code as a string
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * const tspSource = odk.toTypeSpec(schema);
178
+ * console.log(tspSource);
179
+ * ```
180
+ */
181
+ function toTypeSpec(schema: ODKSchema, namespace?: string): string {
182
+ return compiledSchemaToTypeSpec(schema.compiled, namespace);
183
+ }
184
+
185
+ /**
186
+ * Get the compiled schema representation (useful for the Rust CLI).
187
+ *
188
+ * @param schema - ODK schema created with odk.schema()
189
+ * @returns CompiledSchema object
190
+ */
191
+ function getCompiled(schema: ODKSchema): CompiledSchema {
192
+ return schema.compiled;
193
+ }
194
+
195
+ /**
196
+ * Serialize an ODK schema to JSON (for the Rust CLI).
197
+ *
198
+ * @param schema - ODK schema created with odk.schema()
199
+ * @returns JSON string of the compiled schema
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const json = odk.toJSON(schema);
204
+ * await Bun.write("schema.json", json);
205
+ * // Then: tspgen schema.json -o output.tsp
206
+ * ```
207
+ */
208
+ function toJSON(schema: ODKSchema): string {
209
+ return JSON.stringify(schema.compiled, null, 2);
210
+ }
211
+
212
+ /**
213
+ * ODK namespace - main entry point for the library.
214
+ */
215
+ export const odk = {
216
+ schema,
217
+ emit,
218
+ toTypeSpec,
219
+ toJSON,
220
+ getCompiled,
221
+ raw,
222
+ addImport,
223
+ } as const;
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Standard Schema Adapter
3
+ *
4
+ * Converts any Standard Schema-compliant library (Zod, ArkType, Valibot)
5
+ * to ODK's CompiledSchema IR format.
6
+ */
7
+
8
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
9
+ import type {
10
+ CompiledSchema,
11
+ CompiledModel,
12
+ CompiledUnion,
13
+ CompiledField,
14
+ CompiledType,
15
+ FieldConstraints,
16
+ ScalarType,
17
+ } from "./compile.js";
18
+ import {
19
+ extractJsonSchema,
20
+ getSchemaLibrary,
21
+ type JSONSchema,
22
+ } from "./jsonSchemaExtract.js";
23
+
24
+ export interface AdapterOptions {
25
+ /** Suppress warnings about non-serializable constraints */
26
+ suppressWarnings?: boolean;
27
+ }
28
+
29
+ /**
30
+ * Convert a collection of Standard Schema types to CompiledSchema.
31
+ */
32
+ export function standardSchemaToCompiled(
33
+ name: string,
34
+ types: Record<string, unknown>,
35
+ options: AdapterOptions = {},
36
+ ): CompiledSchema {
37
+ const models: CompiledModel[] = [];
38
+ const unions: CompiledUnion[] = [];
39
+ const warnings: string[] = [];
40
+ const processedDefs = new Set<string>();
41
+
42
+ for (const [typeName, schema] of Object.entries(types)) {
43
+ const library = getSchemaLibrary(schema);
44
+
45
+ // Check for non-serializable constraints
46
+ checkSerializability(schema, typeName, warnings);
47
+
48
+ // Extract JSON Schema representation
49
+ const jsonSchema = extractJsonSchema(schema);
50
+
51
+ // Process any $defs/definitions first
52
+ const defs = { ...jsonSchema.$defs, ...jsonSchema.definitions };
53
+ for (const [defName, defSchema] of Object.entries(defs)) {
54
+ if (processedDefs.has(defName)) continue;
55
+ processedDefs.add(defName);
56
+
57
+ const result = jsonSchemaToType(defName, defSchema);
58
+ if (result.model) models.push(result.model);
59
+ if (result.union) unions.push(result.union);
60
+ }
61
+
62
+ // Process the main type
63
+ const result = jsonSchemaToType(typeName, jsonSchema);
64
+ if (result.model) models.push(result.model);
65
+ if (result.union) unions.push(result.union);
66
+ }
67
+
68
+ // Emit warnings
69
+ if (!options.suppressWarnings) {
70
+ for (const warning of warnings) {
71
+ console.warn(`\u26A0\uFE0F ${warning}`);
72
+ }
73
+ }
74
+
75
+ return { name, models, unions, warnings };
76
+ }
77
+
78
+ interface TypeConversionResult {
79
+ model?: CompiledModel;
80
+ union?: CompiledUnion;
81
+ type?: CompiledType;
82
+ }
83
+
84
+ function jsonSchemaToType(
85
+ name: string,
86
+ schema: JSONSchema,
87
+ ): TypeConversionResult {
88
+ // Handle enums as unions
89
+ if (schema.enum) {
90
+ return {
91
+ union: {
92
+ name,
93
+ variants: schema.enum.map((v) => ({
94
+ name: String(v),
95
+ type: { kind: "literal", value: v },
96
+ })),
97
+ description: schema.description,
98
+ },
99
+ };
100
+ }
101
+
102
+ // Handle oneOf/anyOf as unions
103
+ if (schema.oneOf || schema.anyOf) {
104
+ const variants = (schema.oneOf || schema.anyOf)!;
105
+ return {
106
+ union: {
107
+ name,
108
+ variants: variants.map((v, i) => {
109
+ const variantName = v.title || `Variant${i + 1}`;
110
+ return {
111
+ name: variantName,
112
+ type: jsonSchemaPropertyToType(v),
113
+ };
114
+ }),
115
+ description: schema.description,
116
+ },
117
+ };
118
+ }
119
+
120
+ // Handle objects as models
121
+ if (schema.type === "object" || schema.properties) {
122
+ const fields: CompiledField[] = [];
123
+ const required = new Set(schema.required || []);
124
+
125
+ for (const [propName, propSchema] of Object.entries(
126
+ schema.properties || {},
127
+ )) {
128
+ fields.push({
129
+ name: propName,
130
+ type: jsonSchemaPropertyToType(propSchema),
131
+ optional: !required.has(propName),
132
+ description: propSchema.description,
133
+ constraints: extractConstraints(propSchema),
134
+ });
135
+ }
136
+
137
+ return {
138
+ model: {
139
+ name,
140
+ fields,
141
+ description: schema.description,
142
+ },
143
+ };
144
+ }
145
+
146
+ // Handle arrays
147
+ if (schema.type === "array") {
148
+ return {
149
+ type: {
150
+ kind: "array",
151
+ items: schema.items
152
+ ? jsonSchemaPropertyToType(schema.items)
153
+ : { kind: "scalar", name: "unknown" },
154
+ },
155
+ };
156
+ }
157
+
158
+ // Handle refs
159
+ if (schema.$ref) {
160
+ const refName = schema.$ref.split("/").pop() || "Unknown";
161
+ return {
162
+ type: { kind: "ref", name: refName },
163
+ };
164
+ }
165
+
166
+ // Handle primitives - create an alias
167
+ return {
168
+ type: jsonSchemaPropertyToType(schema),
169
+ };
170
+ }
171
+
172
+ function jsonSchemaPropertyToType(schema: JSONSchema): CompiledType {
173
+ // Handle refs
174
+ if (schema.$ref) {
175
+ const refName = schema.$ref.split("/").pop() || "Unknown";
176
+ return { kind: "ref", name: refName };
177
+ }
178
+
179
+ // Handle const
180
+ if (schema.const !== undefined) {
181
+ return {
182
+ kind: "literal",
183
+ value: schema.const as string | number | boolean,
184
+ };
185
+ }
186
+
187
+ // Handle enum (inline)
188
+ if (schema.enum) {
189
+ return {
190
+ kind: "union",
191
+ variants: schema.enum.map((v) => ({
192
+ kind: "literal" as const,
193
+ value: v,
194
+ })),
195
+ };
196
+ }
197
+
198
+ // Handle oneOf/anyOf
199
+ if (schema.oneOf || schema.anyOf) {
200
+ return {
201
+ kind: "union",
202
+ variants: (schema.oneOf || schema.anyOf)!.map((v) =>
203
+ jsonSchemaPropertyToType(v),
204
+ ),
205
+ };
206
+ }
207
+
208
+ // Handle arrays
209
+ if (schema.type === "array") {
210
+ return {
211
+ kind: "array",
212
+ items: schema.items
213
+ ? jsonSchemaPropertyToType(schema.items)
214
+ : { kind: "scalar", name: "unknown" },
215
+ };
216
+ }
217
+
218
+ // Handle objects (inline)
219
+ if (schema.type === "object" || schema.properties) {
220
+ const fields: CompiledField[] = [];
221
+ const required = new Set(schema.required || []);
222
+
223
+ for (const [propName, propSchema] of Object.entries(
224
+ schema.properties || {},
225
+ )) {
226
+ fields.push({
227
+ name: propName,
228
+ type: jsonSchemaPropertyToType(propSchema),
229
+ optional: !required.has(propName),
230
+ constraints: extractConstraints(propSchema),
231
+ });
232
+ }
233
+
234
+ return { kind: "object", fields };
235
+ }
236
+
237
+ // Handle type arrays (union of types)
238
+ if (Array.isArray(schema.type)) {
239
+ return {
240
+ kind: "union",
241
+ variants: schema.type.map((t) => ({
242
+ kind: "scalar" as const,
243
+ name: jsonTypeToScalar(t),
244
+ })),
245
+ };
246
+ }
247
+
248
+ // Handle primitive types
249
+ if (typeof schema.type === "string") {
250
+ return { kind: "scalar", name: jsonTypeToScalar(schema.type) };
251
+ }
252
+
253
+ return { kind: "scalar", name: "unknown" };
254
+ }
255
+
256
+ function jsonTypeToScalar(type: string): ScalarType {
257
+ switch (type) {
258
+ case "string":
259
+ return "string";
260
+ case "number":
261
+ return "float64";
262
+ case "integer":
263
+ return "int64";
264
+ case "boolean":
265
+ return "boolean";
266
+ case "null":
267
+ return "unknown"; // TypeSpec doesn't have null, handle via optional
268
+ default:
269
+ return "unknown";
270
+ }
271
+ }
272
+
273
+ function extractConstraints(schema: JSONSchema): FieldConstraints | undefined {
274
+ const constraints: FieldConstraints = {};
275
+ let hasConstraints = false;
276
+
277
+ if (schema.minLength !== undefined) {
278
+ constraints.minLength = schema.minLength;
279
+ hasConstraints = true;
280
+ }
281
+ if (schema.maxLength !== undefined) {
282
+ constraints.maxLength = schema.maxLength;
283
+ hasConstraints = true;
284
+ }
285
+ if (schema.minimum !== undefined) {
286
+ constraints.minValue = schema.minimum;
287
+ hasConstraints = true;
288
+ }
289
+ if (schema.maximum !== undefined) {
290
+ constraints.maxValue = schema.maximum;
291
+ hasConstraints = true;
292
+ }
293
+ if (schema.exclusiveMinimum !== undefined) {
294
+ constraints.minValue = schema.exclusiveMinimum;
295
+ hasConstraints = true;
296
+ }
297
+ if (schema.exclusiveMaximum !== undefined) {
298
+ constraints.maxValue = schema.exclusiveMaximum;
299
+ hasConstraints = true;
300
+ }
301
+ if (schema.pattern !== undefined) {
302
+ constraints.pattern = schema.pattern;
303
+ hasConstraints = true;
304
+ }
305
+ if (schema.format !== undefined) {
306
+ constraints.format = schema.format;
307
+ hasConstraints = true;
308
+ }
309
+ if (schema.multipleOf !== undefined) {
310
+ constraints.multipleOf = schema.multipleOf;
311
+ hasConstraints = true;
312
+ }
313
+
314
+ return hasConstraints ? constraints : undefined;
315
+ }
316
+
317
+ /**
318
+ * Check for constraints that cannot be serialized to TypeSpec.
319
+ */
320
+ function checkSerializability(
321
+ schema: unknown,
322
+ typeName: string,
323
+ warnings: string[],
324
+ ): void {
325
+ // Zod-specific checks
326
+ if (isZodSchemaWithDef(schema)) {
327
+ const def = schema._def;
328
+
329
+ // Check for transforms
330
+ if (def.typeName === "ZodEffects" && def.effect?.type === "transform") {
331
+ warnings.push(
332
+ `${typeName}: .transform() is not serializable - will be ignored in emission`,
333
+ );
334
+ }
335
+
336
+ // Check for refines
337
+ if (def.typeName === "ZodEffects" && def.effect?.type === "refinement") {
338
+ warnings.push(
339
+ `${typeName}: .refine()/.superRefine() is not serializable - will be ignored in emission`,
340
+ );
341
+ }
342
+
343
+ // Check for preprocessors
344
+ if (def.typeName === "ZodEffects" && def.effect?.type === "preprocess") {
345
+ warnings.push(
346
+ `${typeName}: .preprocess() is not serializable - will be ignored in emission`,
347
+ );
348
+ }
349
+ }
350
+ }
351
+
352
+ function isZodSchemaWithDef(
353
+ schema: unknown,
354
+ ): schema is { _def: { typeName?: string; effect?: { type: string } } } {
355
+ return (
356
+ schema !== null &&
357
+ typeof schema === "object" &&
358
+ "_def" in schema &&
359
+ typeof (schema as Record<string, unknown>)._def === "object"
360
+ );
361
+ }