-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonSchema.kt
563 lines (470 loc) · 12.8 KB
/
JsonSchema.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*
* Copyright 2024 Kazimierz Pogoda / Xemantic
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xemantic.ai.tool.schema
import com.xemantic.ai.tool.schema.serialization.JsonSchemaSerializer
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/**
* Represents a [JSON Schema](https://json-schema.org/) instance.
*/
@Serializable(with = JsonSchemaSerializer::class)
public sealed interface JsonSchema {
/**
* Refers another [JsonSchema] through [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901).
*
* @param ref a string representing JSON Pointer. Note: in JSON it will be serialized as `$ref`.
* @throws IllegalArgumentException if the [ref] does not start with `#/`.
*/
public class Ref(
@SerialName("\$ref")
public val ref: String
) : JsonSchema {
init {
require(ref.startsWith("#/")) {
"The 'ref' must start with '#/'"
}
}
override fun toString(): String = $$"""{"$ref": "$$ref"}"""
}
}
@Serializable
public sealed class BaseSchema(
) : JsonSchema {
public abstract val title: String?
public abstract val description: String?
public open class Builder {
public var title: String? = null
public var description: String? = null
}
override fun toString(): String =
jsonSchemaToStringJson.encodeToString(this)
}
/**
* Schema for JSON objects.
*/
@Serializable
@SerialName("object")
public class ObjectSchema private constructor(
override val title: String? = null,
override val description: String? = null,
public val properties: Map<String, JsonSchema>? = null,
public val required: List<String>? = null,
public val definitions: Map<String, JsonSchema>? = null,
public val additionalProperties: Boolean? = null
) : BaseSchema() {
public class Builder : BaseSchema.Builder() {
public var properties: Map<String, JsonSchema>? = null
public var required: List<String>? = null
public var definitions: Map<String, JsonSchema>? = null
public var additionalProperties: Boolean? = null
public fun build(): ObjectSchema = ObjectSchema(
title,
description,
properties,
required,
definitions,
additionalProperties
)
}
}
public fun ObjectSchema(
block: ObjectSchema.Builder.() -> Unit
): ObjectSchema = ObjectSchema.Builder().also(block).build()
/**
* Schema for JSON arrays
*/
@Serializable
@SerialName("array")
public class ArraySchema private constructor(
override val title: String? = null,
override val description: String? = null,
public val items: JsonSchema,
public val minItems: Long? = null,
public val maxItems: Long? = null,
public val uniqueItems: Boolean? = null,
) : BaseSchema() {
public class Builder : BaseSchema.Builder() {
public var items: JsonSchema? = null
public var minItems: Long? = null
public var maxItems: Long? = null
public var uniqueItems: Boolean? = null
public fun build(): ArraySchema = ArraySchema(
title,
description,
requireNotNull(items) {
"cannot build ArraySchema without 'items' property"
},
minItems,
maxItems,
uniqueItems
)
}
}
public fun ArraySchema(
block: ArraySchema.Builder.() -> Unit
): ArraySchema = ArraySchema.Builder().also(block).build()
public enum class ContentEncoding {
@SerialName("quoted-printable")
QUOTED_PRINTABLE,
@SerialName("base16")
BASE16,
@SerialName("base32")
BASE32,
@SerialName("base64")
BASE64
}
/**
* Schema for strings
*/
@Serializable
@SerialName("string")
public class StringSchema private constructor(
override val title: String? = null,
override val description: String? = null,
public val enum: List<String>? = null,
public val minLength: Long? = null,
public val maxLength: Long? = null,
public val pattern: String? = null,
public val format: String? = null,
public val contentEncoding: ContentEncoding? = null,
public val contentMediaType: String? = null
) : BaseSchema() {
public class Builder : BaseSchema.Builder() {
public var enum: List<String>? = null
public var minLength: Long? = null
public var maxLength: Long? = null
public var pattern: String? = null
public var format: String? = null
public var contentMediaType: String? = null
public var contentEncoding: ContentEncoding? = null
public fun format(format: StringFormat) {
this.format = format.toString()
}
public fun build(): StringSchema = StringSchema(
title,
description,
enum,
minLength,
maxLength,
pattern,
format,
contentEncoding,
contentMediaType
)
}
}
public fun StringSchema(
block: StringSchema.Builder.() -> Unit
): StringSchema = StringSchema.Builder().also(block).build()
public interface NumericSchema<T> {
public val minimum: T?
public val maximum: T?
public val exclusiveMinimum: T?
public val exclusiveMaximum: T?
public val multipleOf: T?
public open class Builder<T> : BaseSchema.Builder() {
public var minimum: T? = null
public var maximum: T? = null
public var exclusiveMinimum: T? = null
public var exclusiveMaximum: T? = null
public var multipleOf: T? = null
}
}
/**
* Schema for numbers (both integer and decimal)
*/
@Serializable
@SerialName("number")
public class NumberSchema private constructor(
override val title: String? = null,
override val description: String? = null,
override val minimum: Double? = null,
override val maximum: Double? = null,
override val exclusiveMinimum: Double? = null,
override val exclusiveMaximum: Double? = null,
override val multipleOf: Double? = null,
) : BaseSchema(), NumericSchema<Double> {
public class Builder : NumericSchema.Builder<Double>() {
public fun build(): NumberSchema = NumberSchema(
title,
description,
minimum,
maximum,
exclusiveMinimum,
exclusiveMaximum,
multipleOf
)
}
}
public fun NumberSchema(
block: NumberSchema.Builder.() -> Unit
): NumberSchema = NumberSchema.Builder().also(block).build()
/**
* Schema specifically for integers
*/
@Serializable
@SerialName("integer")
public class IntegerSchema private constructor(
override val title: String? = null,
override val description: String? = null,
override val minimum: Long? = null,
override val maximum: Long? = null,
override val exclusiveMinimum: Long? = null,
override val exclusiveMaximum: Long? = null,
override val multipleOf: Long? = null,
) : BaseSchema(), NumericSchema<Long> {
public class Builder : NumericSchema.Builder<Long>() {
public fun build(): IntegerSchema = IntegerSchema(
title,
description,
minimum,
maximum,
exclusiveMinimum,
exclusiveMaximum,
multipleOf
)
}
}
public fun IntegerSchema(
block: IntegerSchema.Builder.() -> Unit
): IntegerSchema = IntegerSchema.Builder().also(block).build()
/**
* Schema for boolean values
*/
@Serializable
@SerialName("boolean")
public class BooleanSchema private constructor(
override val title: String? = null,
override val description: String? = null,
) : BaseSchema() {
public class Builder : BaseSchema.Builder() {
public fun build(): BooleanSchema = BooleanSchema(
title,
description
)
}
}
public fun BooleanSchema(
block: BooleanSchema.Builder.() -> Unit
): BooleanSchema = BooleanSchema.Builder().also(block).build()
/**
* Json Schema [`string` formats](https://json-schema.org/understanding-json-schema/reference/string#format).
*/
public enum class StringFormat {
// Dates and times
/**
* A `date-time` format.
*
* E.g., `2018-11-13T20:20:39+00:00`.
*/
DATE_TIME,
/**
* A `time` format.
*
* E.g., `20:20:39+00:00`.
*/
TIME,
/**
* A `date` format.
*
* E.g., `2018-11-13`.
*/
DATE,
/**
* A `duration` format.
*
* E.g., `P3D`.
* See [ISO 8601 ABNF for `duration`](https://datatracker.ietf.org/doc/html/rfc3339#appendix-A).
*/
DURATION,
// Email addresses
/**
* An `email` format.
*
* See [RFC 5321, section 4.1.2](https://datatracker.ietf.org/doc/html/rfc5321#section-4.1.2).
*/
EMAIL,
/**
* An `idn-email` format.
*
* See [RFC 6531](https://datatracker.ietf.org/doc/html/rfc6531).
*/
IDN_EMAIL,
// Hostnames
/**
* A `hostname` format.
*
* See [RFC 1123, section 2.1](https://datatracker.ietf.org/doc/html/rfc1123#section-2.1)
*/
HOSTNAME,
/**
* An `idn-hostname` format.
*
* See [RFC5890, section 2.3.2.3](https://datatracker.ietf.org/doc/html/rfc5890#section-2.3.2.3)
*/
IDN_HOSTNAME,
// IP Addresses
/**
* An `ipv4` format.
*
* IPv4 address, according to dotted-quad ABNF syntax as defined in
* [RFC 2673, section 3.2](https://datatracker.ietf.org/doc/html/rfc2673#section-3.2)
*/
IPV4,
/**
* An `ipv6` format.
*
* IPv6 address, as defined in
* [RFC 2373, section 2.2](http://tools.ietf.org/html/rfc2373#section-2.2)
*/
IPV6,
// Resource identifiers
/**
* A `uuid` format.
*
* A Universally Unique Identifier as defined by [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122).
* Example: `3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a`
*/
UUID,
/**
* A `uri` format.
*
* A universal resource identifier (URI), according to [RFC3986](http://tools.ietf.org/html/rfc3986).
*/
URI,
/**
* A `uri-reference` format.
*
* A URI Reference (either a URI or a relative-reference), according to
* [RFC3986, section 4.1](http://tools.ietf.org/html/rfc3986#section-4.1).
*/
URI_REFERENCE,
/**
* An `iri` format.
*
* The internationalized equivalent of a "uri", according to [RFC3987](https://tools.ietf.org/html/rfc3987).
*/
IRI,
/**
* An `iri-reference` format.
*
* The internationalized equivalent of a "uri-reference", according to [RFC3987](https://tools.ietf.org/html/rfc3987).
*/
IRI_REFERENCE,
/**
* A `uri-template` format.
*
* A URI Template (of any level) according to [RFC6570](https://tools.ietf.org/html/rfc6570).
*/
URI_TEMPLATE,
/**
* A `json-pointer` format.
*
* A JSON Pointer, according to [RFC6901](https://tools.ietf.org/html/rfc6901).
* Should be used only when the entire string contains only JSON Pointer content, e.g. `/foo/bar`.
* JSON Pointer URI fragments, e.g. `#/foo/bar/` should use `URI_REFERENCE`.
*/
JSON_POINTER,
/**
* A `relative-json-pointer` format.
*
* A [relative JSON pointer](https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01).
*/
RELATIVE_JSON_POINTER,
/**
* A `regex` format.
*
* A regular expression, which should be valid according to the
* [ECMA 262](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/) dialect.
*/
REGEX,
// Unofficial formats
/**
* An unofficial `color` format.
*
* Represents a color in hexadecimal format (e.g., "#RRGGBB").
*/
COLOR,
/**
* An unofficial `phone` format.
*
* Represents a phone number. The exact format may vary depending on the implementation.
*/
PHONE,
/**
* An unofficial `credit-card` format.
*
* Represents a credit card number.
*/
CREDIT_CARD,
/**
* An unofficial `isbn` format.
*
* Represents an International Standard Book Number.
*/
ISBN,
/**
* An unofficial `currency` format.
*
* Represents a currency code (e.g., "USD", "EUR").
*/
CURRENCY,
/**
* An unofficial `binary` format.
*
* Represents binary data, typically base64-encoded.
*/
BINARY,
/**
* An unofficial `md5` format.
*
* Represents an MD5 hash.
*/
MD5,
/**
* An unofficial `sha1` format.
*
* Represents a SHA-1 hash.
*/
SHA1,
/**
* An unofficial `sha256` format.
*
* Represents a SHA-256 hash.
*/
SHA256,
/**
* An unofficial `country-code` format.
*
* Represents a country code (e.g., "US", "GB").
*/
COUNTRY_CODE,
/**
* An unofficial `language-code` format.
*
* Represents a language code (e.g., "en", "fr").
*/
LANGUAGE_CODE;
override fun toString(): String = name.lowercase().replace('_', '-')
}
private val jsonSchemaToStringJson = Json {
prettyPrint = true
@OptIn(ExperimentalSerializationApi::class)
prettyPrintIndent = " "
}