|
| 1 | +import type { JSONSchema, JSONSchemaDefinition } from './jsonschema'; |
| 2 | + |
| 3 | +export function toStrictJsonSchema(schema: JSONSchema): JSONSchema { |
| 4 | + return ensureStrictJsonSchema(schema, [], schema); |
| 5 | +} |
| 6 | + |
| 7 | +function ensureStrictJsonSchema( |
| 8 | + jsonSchema: JSONSchemaDefinition, |
| 9 | + path: string[], |
| 10 | + root: JSONSchema, |
| 11 | +): JSONSchema { |
| 12 | + /** |
| 13 | + * Mutates the given JSON schema to ensure it conforms to the `strict` standard |
| 14 | + * that the API expects. |
| 15 | + */ |
| 16 | + if (typeof jsonSchema === 'boolean') { |
| 17 | + throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`); |
| 18 | + } |
| 19 | + |
| 20 | + if (!isDict(jsonSchema)) { |
| 21 | + throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be a dictionary; path=${path.join('/')}`); |
| 22 | + } |
| 23 | + |
| 24 | + // Handle $defs (non-standard but sometimes used) |
| 25 | + const defs = (jsonSchema as any).$defs; |
| 26 | + if (isDict(defs)) { |
| 27 | + for (const [defName, defSchema] of Object.entries(defs)) { |
| 28 | + ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // Handle definitions (draft-04 style, deprecated in draft-07 but still used) |
| 33 | + const definitions = (jsonSchema as any).definitions; |
| 34 | + if (isDict(definitions)) { |
| 35 | + for (const [definitionName, definitionSchema] of Object.entries(definitions)) { |
| 36 | + ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // Add additionalProperties: false to object types |
| 41 | + const typ = jsonSchema.type; |
| 42 | + if (typ === 'object' && !('additionalProperties' in jsonSchema)) { |
| 43 | + jsonSchema.additionalProperties = false; |
| 44 | + } |
| 45 | + |
| 46 | + // Handle object properties |
| 47 | + const properties = jsonSchema.properties; |
| 48 | + if (isDict(properties)) { |
| 49 | + jsonSchema.required = Object.keys(properties); |
| 50 | + jsonSchema.properties = Object.fromEntries( |
| 51 | + Object.entries(properties).map(([key, propSchema]) => [ |
| 52 | + key, |
| 53 | + ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root), |
| 54 | + ]), |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + // Handle arrays |
| 59 | + const items = jsonSchema.items; |
| 60 | + if (isDict(items)) { |
| 61 | + // @ts-ignore(2345) |
| 62 | + jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root); |
| 63 | + } |
| 64 | + |
| 65 | + // Handle unions (anyOf) |
| 66 | + const anyOf = jsonSchema.anyOf; |
| 67 | + if (Array.isArray(anyOf)) { |
| 68 | + jsonSchema.anyOf = anyOf.map((variant, i) => |
| 69 | + ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root), |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + // Handle intersections (allOf) |
| 74 | + const allOf = jsonSchema.allOf; |
| 75 | + if (Array.isArray(allOf)) { |
| 76 | + if (allOf.length === 1) { |
| 77 | + const resolved = ensureStrictJsonSchema(allOf[0]!, [...path, 'allOf', '0'], root); |
| 78 | + Object.assign(jsonSchema, resolved); |
| 79 | + delete jsonSchema.allOf; |
| 80 | + } else { |
| 81 | + jsonSchema.allOf = allOf.map((entry, i) => |
| 82 | + ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root), |
| 83 | + ); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + // Strip `null` defaults as there's no meaningful distinction |
| 88 | + if (jsonSchema.default === null) { |
| 89 | + delete jsonSchema.default; |
| 90 | + } |
| 91 | + |
| 92 | + // Handle $ref with additional properties |
| 93 | + const ref = (jsonSchema as any).$ref; |
| 94 | + if (ref && hasMoreThanNKeys(jsonSchema, 1)) { |
| 95 | + if (typeof ref !== 'string') { |
| 96 | + throw new TypeError(`Received non-string $ref - ${ref}`); |
| 97 | + } |
| 98 | + |
| 99 | + const resolved = resolveRef(root, ref); |
| 100 | + if (typeof resolved === 'boolean') { |
| 101 | + throw new ValueError(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`); |
| 102 | + } |
| 103 | + if (!isDict(resolved)) { |
| 104 | + throw new ValueError( |
| 105 | + `Expected \`$ref: ${ref}\` to resolve to a dictionary but got ${JSON.stringify(resolved)}`, |
| 106 | + ); |
| 107 | + } |
| 108 | + |
| 109 | + // Properties from the json schema take priority over the ones on the `$ref` |
| 110 | + Object.assign(jsonSchema, { ...resolved, ...jsonSchema }); |
| 111 | + delete (jsonSchema as any).$ref; |
| 112 | + |
| 113 | + // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied, |
| 114 | + // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid. |
| 115 | + return ensureStrictJsonSchema(jsonSchema, path, root); |
| 116 | + } |
| 117 | + |
| 118 | + return jsonSchema; |
| 119 | +} |
| 120 | + |
| 121 | +function resolveRef(root: JSONSchema, ref: string): JSONSchemaDefinition { |
| 122 | + if (!ref.startsWith('#/')) { |
| 123 | + throw new ValueError(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`); |
| 124 | + } |
| 125 | + |
| 126 | + const pathParts = ref.slice(2).split('/'); |
| 127 | + let resolved: any = root; |
| 128 | + |
| 129 | + for (const key of pathParts) { |
| 130 | + if (!isDict(resolved)) { |
| 131 | + throw new Error( |
| 132 | + `encountered non-dictionary entry while resolving ${ref} - ${JSON.stringify(resolved)}`, |
| 133 | + ); |
| 134 | + } |
| 135 | + const value = resolved[key]; |
| 136 | + if (value === undefined) { |
| 137 | + throw new Error(`Key ${key} not found while resolving ${ref}`); |
| 138 | + } |
| 139 | + resolved = value; |
| 140 | + } |
| 141 | + |
| 142 | + return resolved; |
| 143 | +} |
| 144 | + |
| 145 | +function isDict(obj: any): obj is Record<string, any> { |
| 146 | + return typeof obj === 'object' && obj !== null && !Array.isArray(obj); |
| 147 | +} |
| 148 | + |
| 149 | +function hasMoreThanNKeys(obj: Record<string, any>, n: number): boolean { |
| 150 | + let i = 0; |
| 151 | + for (const _ in obj) { |
| 152 | + i++; |
| 153 | + if (i > n) { |
| 154 | + return true; |
| 155 | + } |
| 156 | + } |
| 157 | + return false; |
| 158 | +} |
| 159 | + |
| 160 | +class ValueError extends Error { |
| 161 | + constructor(message: string) { |
| 162 | + super(message); |
| 163 | + this.name = 'ValueError'; |
| 164 | + } |
| 165 | +} |
0 commit comments