[79a0317] | 1 | import type {MacroKeywordDefinition, SchemaObject, Schema} from "ajv"
|
---|
| 2 | import type {DefinitionOptions} from "./_types"
|
---|
| 3 | import {metaSchemaRef} from "./_util"
|
---|
| 4 |
|
---|
| 5 | export default function getDef(opts?: DefinitionOptions): MacroKeywordDefinition {
|
---|
| 6 | return {
|
---|
| 7 | keyword: "deepProperties",
|
---|
| 8 | type: "object",
|
---|
| 9 | schemaType: "object",
|
---|
| 10 | macro: function (schema: Record<string, SchemaObject>) {
|
---|
| 11 | const allOf = []
|
---|
| 12 | for (const pointer in schema) allOf.push(getSchema(pointer, schema[pointer]))
|
---|
| 13 | return {allOf}
|
---|
| 14 | },
|
---|
| 15 | metaSchema: {
|
---|
| 16 | type: "object",
|
---|
| 17 | propertyNames: {type: "string", format: "json-pointer"},
|
---|
| 18 | additionalProperties: metaSchemaRef(opts),
|
---|
| 19 | },
|
---|
| 20 | }
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | function getSchema(jsonPointer: string, schema: SchemaObject): SchemaObject {
|
---|
| 24 | const segments = jsonPointer.split("/")
|
---|
| 25 | const rootSchema: SchemaObject = {}
|
---|
| 26 | let pointerSchema: SchemaObject = rootSchema
|
---|
| 27 | for (let i = 1; i < segments.length; i++) {
|
---|
| 28 | let segment: string = segments[i]
|
---|
| 29 | const isLast = i === segments.length - 1
|
---|
| 30 | segment = unescapeJsonPointer(segment)
|
---|
| 31 | const properties: Record<string, Schema> = (pointerSchema.properties = {})
|
---|
| 32 | let items: SchemaObject[] | undefined
|
---|
| 33 | if (/[0-9]+/.test(segment)) {
|
---|
| 34 | let count = +segment
|
---|
| 35 | items = pointerSchema.items = []
|
---|
| 36 | pointerSchema.type = ["object", "array"]
|
---|
| 37 | while (count--) items.push({})
|
---|
| 38 | } else {
|
---|
| 39 | pointerSchema.type = "object"
|
---|
| 40 | }
|
---|
| 41 | pointerSchema = isLast ? schema : {}
|
---|
| 42 | properties[segment] = pointerSchema
|
---|
| 43 | if (items) items.push(pointerSchema)
|
---|
| 44 | }
|
---|
| 45 | return rootSchema
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | function unescapeJsonPointer(str: string): string {
|
---|
| 49 | return str.replace(/~1/g, "/").replace(/~0/g, "~")
|
---|
| 50 | }
|
---|
| 51 |
|
---|
| 52 | module.exports = getDef
|
---|