-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJSONSchema.swift
450 lines (406 loc) · 14.6 KB
/
JSONSchema.swift
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
//
// JSONSchema.swift
// DynamicJSONTests
//
// Created by Matthias Zenger on 18/03/2024.
// Copyright © 2024 Matthias Zenger. All rights reserved.
//
// 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.
//
import Foundation
///
/// Representation of a JSON schema. A JSON schema is either boolean (i.e. validation
/// yields always true or false), or it is a collection of keywords specified by a
/// "descriptor". The descriptor is a structured interpretation of a schema definition
/// provided as a second parameter to case `descriptor`.
///
/// `JSONSchema` values are almost never created individually, e.g. by using the
/// cases defined below. They are typically managed via a `JSONSchemaResource`. Thus
/// class `JSONSchemaResource` handles parsing strings and binary data and converting
/// them into valid `JSONSchema` objects.
///
public indirect enum JSONSchema: Codable,
Equatable,
CustomDebugStringConvertible {
case boolean(Bool)
case descriptor(JSONSchemaDescriptor, JSON)
/// Collection of errors raised by functionality provided by `JSONSchema`.
public enum Error: LocalizedError, CustomStringConvertible {
case cannotDecodeString
public var description: String {
switch self {
case .cannotDecodeString:
return "cannot decode string into a JSON schema"
}
}
public var errorDescription: String? {
return self.description
}
public var failureReason: String? {
switch self {
case .cannotDecodeString:
return "decoding error"
}
}
}
/// Initializes a schema from a `Data` value. The given schema
/// identifier `id` is only used if the schema does not define one itself.
public init(data: Data, id: JSONSchemaIdentifier? = nil) throws {
let schema = try JSONDecoder().decode(JSONSchema.self, from: data)
switch schema {
case .boolean(_):
self = schema
case .descriptor(var descriptor, let json):
if descriptor.id == nil {
descriptor.id = id
}
self = .descriptor(descriptor, json)
}
}
/// Initializes a schema from a string representation. The given schema
/// identifier `id` is only used if the schema does not define one itself.
public init(string: String, id: JSONSchemaIdentifier? = nil) throws {
guard let data = string.data(using: .utf8) else {
throw Error.cannotDecodeString
}
try self.init(data: data, id: id)
}
/// Initializes a schema from a URL for the given default JSON schema identifier.
/// The given schema identifier `id` is only used if the schema does not define one itself.
public init(url: URL, id: JSONSchemaIdentifier? = nil) throws {
try self.init(data: try Data(contentsOf: url), id: id)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let object = try? container.decode(JSONSchemaDescriptor.self),
let json = try? container.decode(JSON.self) {
self = .descriptor(object, json)
} else if let bool = try? container.decode(Bool.self) {
self = .boolean(bool)
} else {
throw DecodingError.dataCorrupted(
DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid JSONSchema encoding"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .boolean(let bool):
try container.encode(bool)
case .descriptor(_, let json):
try container.encode(json)
}
}
public var isBoolean: Bool {
switch self {
case .boolean(_):
return true
case .descriptor(_, _):
return false
}
}
public var id: JSONSchemaIdentifier? {
switch self {
case .boolean(_):
return nil
case .descriptor(let descriptor, _):
return descriptor.id
}
}
public var schema: URL? {
switch self {
case .boolean(_):
return nil
case .descriptor(let descriptor, _):
return descriptor.schema
}
}
public var title: String? {
switch self {
case .boolean(_):
return nil
case .descriptor(let descriptor, _):
return descriptor.title
}
}
public var debugDescription: String {
switch self {
case .boolean(false):
return "false"
case .boolean(true):
return "true"
case .descriptor(let descriptor, _):
return descriptor.debugDescription
}
}
public var schemaObjects: [JSONLocation : JSONSchema] {
guard case .descriptor(let descriptor, _) = self else {
return [:]
}
var res: [JSONLocation : JSONSchema] = [:]
self.insert(into: &res, at: .root, uri: descriptor.id)
return res
}
fileprivate func insert(into nested: inout [JSONLocation : JSONSchema],
at location: JSONLocation,
uri base: JSONSchemaIdentifier?) {
switch self {
case .boolean(_):
nested[location] = self
case .descriptor(var descriptor, let json):
if let id = descriptor.id {
descriptor.id = id.relative(to: base)
}
nested[location] = .descriptor(descriptor, json)
descriptor.insert(into: &nested, at: location, uri: descriptor.id ?? base)
}
}
}
///
/// `JSONSchemaDescriptor` provides a structured representation of all the
/// keywords defined by the JSON Schema Draft 2020 standard.
///
public struct JSONSchemaDescriptor: Codable, Equatable, CustomDebugStringConvertible {
// Core vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/core
public var id: JSONSchemaIdentifier?
public let schema: URL?
public let anchor: String?
public let ref: JSONSchemaIdentifier?
public let dynamicRef: JSONSchemaIdentifier?
public let dynamicAnchor: String?
public let vocabulary: [String : Bool]?
public let comment: String?
public let defs: [String : JSONSchema]?
// Applicator vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/applicator
public let prefixItems: [JSONSchema]?
public let items: JSONSchema?
public let contains: JSONSchema?
public let additionalProperties: JSONSchema?
public let properties: [String : JSONSchema]?
public let patternProperties: [String : JSONSchema]?
public let dependentSchemas: [String : JSONSchema]?
public let propertyNames: JSONSchema?
public let `if`: JSONSchema?
public let `then`: JSONSchema?
public let `else`: JSONSchema?
public let allOf: [JSONSchema]?
public let anyOf: [JSONSchema]?
public let oneOf: [JSONSchema]?
public let not: JSONSchema?
// Unevaluated applicator vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/unevaluated
public let unevaluatedItems: JSONSchema?
public let unevaluatedProperties: JSONSchema?
// Validation vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/validation
public let multipleOf: Double?
public let maximum: Double?
public let exclusiveMaximum: Double?
public let minimum: Double?
public let exclusiveMinimum: Double?
public let maxLength: UInt?
public let minLength: UInt?
public let pattern: String?
public let maxItems: UInt?
public let minItems: UInt?
public let uniqueItems: Bool?
public let maxContains: UInt?
public let minContains: UInt?
public let maxProperties: UInt?
public let minProperties: UInt?
public let required: [String]?
public let dependentRequired: [String : [String]]?
public let const: JSON?
public let `enum`: [JSON]?
public let type: JSONType?
// Meta-data vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/meta-data
public let title: String?
public let description: String?
public let `default`: JSON?
public let deprecated: Bool?
public let readOnly: Bool?
public let writeOnly: Bool?
public let examples: [JSON]?
// Format vocabulary meta-schema for annotation results
// https://json-schema.org/draft/2020-12/meta/format-annotation
public let format: String?
// Content vocabulary meta-schema
// https://json-schema.org/draft/2020-12/meta/content
public let contentMediaType: String?
public let contentEncoding: String?
public let contentSchema: JSONSchema?
// For backward compatibility
public let definitions: [String : JSONSchema]?
public let dependencies: [String : JSONSchemaDependency]?
public var debugDescription: String {
do {
let json = try JSON(encodable: self)
if let str = try json.string(formatting: .prettyPrinted, dateEncodingStrategy: .iso8601) {
return str
}
} catch {
}
return "{ id = \(self.id?.string ?? "nil"), ... }"
}
/// Collect nested JSONSchema definitions
fileprivate func insert(into nested: inout [JSONLocation : JSONSchema],
at location: JSONLocation,
uri base: JSONSchemaIdentifier?) {
self.defs?.insert(into: &nested, at: .member(location, "$defs"), uri: base)
self.prefixItems?.insert(into: &nested, at: .member(location, "prefixItems"), uri: base)
self.items?.insert(into: &nested, at: .member(location, "items"), uri: base)
self.contains?.insert(into: &nested, at: .member(location, "contains"), uri: base)
self.additionalProperties?.insert(into: &nested, at: .member(location, "additionalProperties"), uri: base)
self.properties?.insert(into: &nested, at: .member(location, "properties"), uri: base)
self.patternProperties?.insert(into: &nested, at: .member(location, "patternProperties"), uri: base)
self.dependentSchemas?.insert(into: &nested, at: .member(location, "dependentSchemas"), uri: base)
self.propertyNames?.insert(into: &nested, at: .member(location, "propertyNames"), uri: base)
self.if?.insert(into: &nested, at: .member(location, "if"), uri: base)
self.then?.insert(into: &nested, at: .member(location, "then"), uri: base)
self.else?.insert(into: &nested, at: .member(location, "else"), uri: base)
self.allOf?.insert(into: &nested, at: .member(location, "allOf"), uri: base)
self.anyOf?.insert(into: &nested, at: .member(location, "anyOf"), uri: base)
self.oneOf?.insert(into: &nested, at: .member(location, "oneOf"), uri: base)
self.not?.insert(into: &nested, at: .member(location, "not"), uri: base)
self.unevaluatedItems?.insert(into: &nested, at: .member(location, "unevaluatedItems"), uri: base)
self.unevaluatedProperties?.insert(into: &nested, at: .member(location, "unevaluatedProperties"), uri: base)
self.contentSchema?.insert(into: &nested, at: .member(location, "contentSchema"), uri: base)
self.definitions?.insert(into: &nested, at: .member(location, "definitions"), uri: base)
self.dependencies?.insert(into: &nested, at: .member(location, "dependencies"), uri: base)
}
public enum CodingKeys: String, CodingKey {
case id = "$id"
case schema = "$schema"
case anchor = "$anchor"
case ref = "$ref"
case dynamicRef = "$dynamicRef"
case dynamicAnchor = "$dynamicAnchor"
case vocabulary = "$vocabulary"
case comment = "$comment"
case defs = "$defs"
case prefixItems
case items
case contains
case additionalProperties
case properties
case patternProperties
case dependentSchemas
case propertyNames
case `if`
case `then`
case `else`
case allOf
case anyOf
case oneOf
case not
case unevaluatedItems
case unevaluatedProperties
case multipleOf
case maximum
case exclusiveMaximum
case minimum
case exclusiveMinimum
case maxLength
case minLength
case pattern
case maxItems
case minItems
case uniqueItems
case maxContains
case minContains
case maxProperties
case minProperties
case required
case dependentRequired
case const
case `enum`
case type
case title
case description
case `default`
case deprecated
case readOnly
case writeOnly
case examples
case format
case contentMediaType
case contentEncoding
case contentSchema
case definitions
case dependencies
}
}
///
/// Representation of the `dependencies` keyword.
///
public indirect enum JSONSchemaDependency: Codable, Equatable {
case array([String])
case schema(JSONSchema)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let arr = try? container.decode([String].self) {
self = .array(arr)
} else if let object = try? container.decode(JSONSchema.self) {
self = .schema(object)
} else {
throw DecodingError.dataCorrupted(
DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid JSONSchemaDependency encoding"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .array(let arr):
try container.encode(arr)
case .schema(let schema):
try container.encode(schema)
}
}
}
extension Array<JSONSchema> {
fileprivate func insert(into nested: inout [JSONLocation : JSONSchema],
at location: JSONLocation,
uri base: JSONSchemaIdentifier?) {
for i in self.indices {
self[i].insert(into: &nested, at: .index(location, i), uri: base)
}
}
}
extension Dictionary<String, JSONSchema> {
fileprivate func insert(into nested: inout [JSONLocation : JSONSchema],
at location: JSONLocation,
uri base: JSONSchemaIdentifier?) {
for (key, value) in self {
value.insert(into: &nested, at: .member(location, key), uri: base)
}
}
}
extension Dictionary<String, JSONSchemaDependency> {
fileprivate func insert(into nested: inout [JSONLocation : JSONSchema],
at location: JSONLocation,
uri base: JSONSchemaIdentifier?) {
for (key, value) in self {
switch value {
case .array(_):
break
case .schema(let schema):
schema.insert(into: &nested, at: .member(location, key), uri: base)
}
}
}
}