Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234//! Argument field types that carry their JSON schema options.
const std = @import("std");
const Stringify = std.json.Stringify;const WriterError = std.Io.Writer.Error;
pub const StringOptions = struct { description: []const u8, min_length: ?i64 = null, max_length: ?i64 = null,};
pub const IntegerOptions = struct { description: []const u8, min: ?i64 = null, max: ?i64 = null,};
pub const ArrayOptions = struct { description: []const u8, min_items: ?i64 = null,};
pub fn String(comptime options: StringOptions) type { return struct { value: []const u8 = "",
pub const expected = "a string" ++ if (options.min_length != null and options.max_length != null) std.fmt.comptimePrint(" of {d} to {d} character(s)", .{ options.min_length.?, options.max_length.? }) else if (options.min_length) |min| std.fmt.comptimePrint(" of at least {d} character(s)", .{min}) else if (options.max_length) |max| std.fmt.comptimePrint(" of at most {d} character(s)", .{max}) else "";
pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, parse_options: std.json.ParseOptions) std.json.ParseError(@TypeOf(source.*))!@This() { const value = try std.json.innerParse([]const u8, allocator, source, parse_options); if (options.min_length != null or options.max_length != null) { // The JSON scanner rejects invalid UTF-8 and unpaired surrogates. const length = std.unicode.utf8CountCodepoints(value) catch unreachable; if (length < options.min_length orelse 0 or length > options.max_length orelse std.math.maxInt(i64)) { return error.LengthMismatch; } } return .{ .value = value }; }
pub fn writeSchema(jw: *Stringify) WriterError!void { try writeScalar(jw, "string", options); } };}
pub fn Integer(comptime options: IntegerOptions) type { return struct { value: i64 = 0,
pub const expected = "an integer" ++ if (options.min != null and options.max != null) std.fmt.comptimePrint(" from {d} to {d}", .{ options.min.?, options.max.? }) else if (options.min) |min| std.fmt.comptimePrint(" of at least {d}", .{min}) else if (options.max) |max| std.fmt.comptimePrint(" of at most {d}", .{max}) else "";
pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, parse_options: std.json.ParseOptions) std.json.ParseError(@TypeOf(source.*))!@This() { const value = try std.json.innerParse(i64, allocator, source, parse_options); // Overflow is the only parse error the JSON layer offers for a number out of range. if (options.min) |min| { if (value < min) { return error.Overflow; } } if (options.max) |max| { if (value > max) { return error.Overflow; } } return .{ .value = value }; }
pub fn writeSchema(jw: *Stringify) WriterError!void { try writeScalar(jw, "integer", options); } };}
pub fn Array(comptime Item: type, comptime options: ArrayOptions) type { return struct { items: []const Item = &.{},
pub const Element = Item; pub const expected = "an array" ++ if (options.min_items) |min| std.fmt.comptimePrint(" of at least {d} item(s)", .{min}) else "";
pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, parse_options: std.json.ParseOptions) std.json.ParseError(@TypeOf(source.*))!@This() { const items = try std.json.innerParse([]const Item, allocator, source, parse_options); if (options.min_items) |min| { if (items.len < min) { return error.LengthMismatch; } } return .{ .items = items }; }
pub fn writeSchema(jw: *Stringify) WriterError!void { try jw.beginObject(); try jw.objectField("type"); try jw.write("array"); try writeDescription(jw, options); try jw.objectField("items"); try writeJson(jw, Item); try writeConstraints(jw, options); try jw.endObject(); } };}
/// JSON schema for a type, built at comptime.pub fn schemaJson(comptime T: type) []const u8 { return comptime blk: { @setEvalBranchQuota(200_000); var buffer: [16 * 1024]u8 = undefined; var writer: std.Io.Writer = .fixed(&buffer); var jw: Stringify = .{ .writer = &writer }; writeJson(&jw, T) catch unreachable; const text: [writer.end]u8 = buffer[0..writer.end].*; break :blk &text; };}
fn writeJson(jw: *Stringify, comptime T: type) WriterError!void { switch (@typeInfo(T)) { .optional => |info| try writeJson(jw, info.child), .@"struct" => |info| { if (@hasDecl(T, "writeSchema")) { return T.writeSchema(jw); }
try jw.beginObject(); try jw.objectField("type"); try jw.write("object"); try jw.objectField("properties"); try jw.beginObject(); inline for (info.field_names, info.field_types) |name, FieldType| { try jw.objectField(name); try writeJson(jw, FieldType); } try jw.endObject(); try jw.objectField("required"); try jw.beginArray(); inline for (info.field_names, info.field_types, info.field_attrs) |name, FieldType, attrs| { if (attrs.defaultValue(FieldType) != null) { continue; } try jw.write(name); } try jw.endArray(); try jw.endObject(); }, else => @compileError("unsupported tool argument type: " ++ @typeName(T)), }}
fn writeScalar(jw: *Stringify, comptime type_name: []const u8, comptime options: anytype) WriterError!void { try jw.beginObject(); try jw.objectField("type"); try jw.write(type_name); try writeDescription(jw, options); try writeConstraints(jw, options); try jw.endObject();}
fn writeDescription(jw: *Stringify, comptime options: anytype) WriterError!void { try jw.objectField("description"); try jw.write(options.description);}
fn writeConstraints(jw: *Stringify, comptime options: anytype) WriterError!void { try writeOption(jw, options, "min", "minimum"); try writeOption(jw, options, "max", "maximum"); try writeOption(jw, options, "min_items", "minItems"); try writeOption(jw, options, "min_length", "minLength"); try writeOption(jw, options, "max_length", "maxLength");}
fn writeOption(jw: *Stringify, comptime options: anytype, comptime field: []const u8, comptime key: []const u8) WriterError!void { if (!@hasField(@TypeOf(options), field)) { return; } if (@field(options, field)) |value| { try jw.objectField(key); try jw.write(value); }}
const Limited = struct { value: String(.{ .description = "d", .min_length = 2, .max_length = 3 }),};
test "string length limits appear in the schema and the expected text" { try std.testing.expectEqualStrings( "{\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"string\",\"description\":\"d\",\"minLength\":2,\"maxLength\":3}},\"required\":[\"value\"]}", schemaJson(Limited), ); try std.testing.expectEqualStrings("a string of 2 to 3 character(s)", @FieldType(Limited, "value").expected);}
test "string length limits count characters, not bytes" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); for ([_][]const u8{ "\u{e9}\u{e9}", "\u{e9}\u{e9}\u{e9}" }) |value| { const json = try std.fmt.allocPrint(arena, "{{\"value\":\"{s}\"}}", .{value}); try std.testing.expectEqualStrings(value, (try std.json.parseFromSliceLeaky(Limited, arena, json, .{})).value.value); } for ([_][]const u8{ "\u{e9}", "abcd" }) |value| { const json = try std.fmt.allocPrint(arena, "{{\"value\":\"{s}\"}}", .{value}); try std.testing.expectError(error.LengthMismatch, std.json.parseFromSliceLeaky(Limited, arena, json, .{})); }}
test "schema descriptions are JSON escaped" { const Escaped = struct { value: String(.{ .description = "a \"quoted\"\nline" }), }; try std.testing.expectEqualStrings( "{\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"string\",\"description\":\"a \\\"quoted\\\"\\nline\"}},\"required\":[\"value\"]}", schemaJson(Escaped), );}