id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,500 | function returnResults(it: SchemaCxt): void {
const {gen, schemaEnv, validateName, ValidationError, opts} = it
if (schemaEnv.$async) {
// TODO assign unevaluated
gen.if(
_`${N.errors} === 0`,
() => gen.return(N.data),
() => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
)
} else {
gen.assign(_`${validateName}.errors`, N.vErrors)
if (opts.unevaluated) assignEvaluated(it)
gen.return(_`${N.errors} === 0`)
}
} | interface SchemaCxt {
readonly gen: CodeGen
readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
readonly data: Name // Name with reference to the current part of data instance
readonly parentData: Name // should be used in keywords modifying data
readonly parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
definedProperties: Set<string> // set of properties to keep track of for required checks
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
} |
2,501 | function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
} | interface SchemaCxt {
readonly gen: CodeGen
readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
readonly data: Name // Name with reference to the current part of data instance
readonly parentData: Name // should be used in keywords modifying data
readonly parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
definedProperties: Set<string> // set of properties to keep track of for required checks
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
} |
2,502 | function schemaKeywords(
it: SchemaObjCxt,
types: JSONType[],
typeErrors: boolean,
errsCount?: Name
): void {
const {gen, schema, data, allErrors, opts, self} = it
const {RULES} = self
if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
return
}
if (!opts.jtd) checkStrictTypes(it, types)
gen.block(() => {
for (const group of RULES.rules) groupKeywords(group)
groupKeywords(RULES.post)
})
function groupKeywords(group: RuleGroup): void {
if (!shouldUseGroup(schema, group)) return
if (group.type) {
gen.if(checkDataType(group.type, data, opts.strictNumbers))
iterateKeywords(it, group)
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else()
reportTypeError(it)
}
gen.endIf()
} else {
iterateKeywords(it, group)
}
// TODO make it "ok" call?
if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,503 | function schemaKeywords(
it: SchemaObjCxt,
types: JSONType[],
typeErrors: boolean,
errsCount?: Name
): void {
const {gen, schema, data, allErrors, opts, self} = it
const {RULES} = self
if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
return
}
if (!opts.jtd) checkStrictTypes(it, types)
gen.block(() => {
for (const group of RULES.rules) groupKeywords(group)
groupKeywords(RULES.post)
})
function groupKeywords(group: RuleGroup): void {
if (!shouldUseGroup(schema, group)) return
if (group.type) {
gen.if(checkDataType(group.type, data, opts.strictNumbers))
iterateKeywords(it, group)
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else()
reportTypeError(it)
}
gen.endIf()
} else {
iterateKeywords(it, group)
}
// TODO make it "ok" call?
if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
}
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,504 | function groupKeywords(group: RuleGroup): void {
if (!shouldUseGroup(schema, group)) return
if (group.type) {
gen.if(checkDataType(group.type, data, opts.strictNumbers))
iterateKeywords(it, group)
if (types.length === 1 && types[0] === group.type && typeErrors) {
gen.else()
reportTypeError(it)
}
gen.endIf()
} else {
iterateKeywords(it, group)
}
// TODO make it "ok" call?
if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
} | interface RuleGroup {
type?: JSONType
rules: Rule[]
} |
2,505 | function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
const {
gen,
schema,
opts: {useDefaults},
} = it
if (useDefaults) assignDefaults(it, group.type)
gen.block(() => {
for (const rule of group.rules) {
if (shouldUseRule(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type)
}
}
})
} | interface RuleGroup {
type?: JSONType
rules: Rule[]
} |
2,506 | function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
const {
gen,
schema,
opts: {useDefaults},
} = it
if (useDefaults) assignDefaults(it, group.type)
gen.block(() => {
for (const rule of group.rules) {
if (shouldUseRule(schema, rule)) {
keywordCode(it, rule.keyword, rule.definition, group.type)
}
}
})
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,507 | function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
if (it.schemaEnv.meta || !it.opts.strictTypes) return
checkContextTypes(it, types)
if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
checkKeywordTypes(it, it.dataTypes)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,508 | function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
if (!types.length) return
if (!it.dataTypes.length) {
it.dataTypes = types
return
}
types.forEach((t) => {
if (!includesType(it.dataTypes, t)) {
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
}
})
narrowSchemaTypes(it, types)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,509 | function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
strictTypesError(it, "use allowUnionTypes to allow union type keyword")
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,510 | function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
const rules = it.self.RULES.all
for (const keyword in rules) {
const rule = rules[keyword]
if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
const {type} = rule.definition
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
}
}
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,511 | function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
const ts: JSONType[] = []
for (const t of it.dataTypes) {
if (includesType(withTypes, t)) ts.push(t)
else if (withTypes.includes("integer") && t === "number") ts.push("integer")
}
it.dataTypes = ts
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,512 | function strictTypesError(it: SchemaObjCxt, msg: string): void {
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
msg += ` at "${schemaPath}" (strictTypes)`
checkStrictMode(it, msg, it.opts.strictTypes)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,513 | constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
} | type AddedKeywordDefinition = KeywordDefinition & {
type: JSONType[]
schemaType: JSONType[]
} |
2,514 | constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,515 | result(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.failResult(not(condition), successAction, failAction)
} | type Code = _Code | Name |
2,516 | failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.gen.if(condition)
if (failAction) failAction()
else this.error()
if (successAction) {
this.gen.else()
successAction()
if (this.allErrors) this.gen.endIf()
} else {
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
} | type Code = _Code | Name |
2,517 | pass(condition: Code, failAction?: () => void): void {
this.failResult(not(condition), undefined, failAction)
} | type Code = _Code | Name |
2,518 | fail(condition?: Code): void {
if (condition === undefined) {
this.error()
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
return
}
this.gen.if(condition)
this.error()
if (this.allErrors) this.gen.endIf()
else this.gen.else()
} | type Code = _Code | Name |
2,519 | fail$data(condition: Code): void {
if (!this.$data) return this.fail(condition)
const {schemaCode} = this
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
} | type Code = _Code | Name |
2,520 | setParams(obj: KeywordCxtParams, assign?: true): void {
if (assign) Object.assign(this.params, obj)
else this.params = obj
} | type KeywordCxtParams = {[P in string]?: Code | string | number} |
2,521 | block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,522 | block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
} | type Code = _Code | Name |
2,523 | check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,524 | check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
} | type Code = _Code | Name |
2,525 | subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
} | type SubschemaArgs = Partial<{
keyword: string
schemaProp: string | number
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef: Code
data: Name | Code
dataProp: Code | string | number
dataTypes: JSONType[]
definedProperties: Set<string>
propertyName: Name
dataPropType: Type
jtdDiscriminator: string
jtdMetadata: boolean
compositeRule: true
createErrors: boolean
allErrors: boolean
}> |
2,526 | subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,527 | mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
const {it, gen} = this
if (!it.opts.unevaluated) return
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
}
} | interface SchemaCxt {
readonly gen: CodeGen
readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
readonly data: Name // Name with reference to the current part of data instance
readonly parentData: Name // should be used in keywords modifying data
readonly parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
definedProperties: Set<string> // set of properties to keep track of for required checks
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
} |
2,528 | mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,529 | mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
} | interface SchemaCxt {
readonly gen: CodeGen
readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
readonly data: Name // Name with reference to the current part of data instance
readonly parentData: Name // should be used in keywords modifying data
readonly parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
definedProperties: Set<string> // set of properties to keep track of for required checks
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
} |
2,530 | function keywordCode(
it: SchemaObjCxt,
keyword: string,
def: AddedKeywordDefinition,
ruleType?: JSONType
): void {
const cxt = new KeywordCxt(it, def, keyword)
if ("code" in def) {
def.code(cxt, ruleType)
} else if (cxt.$data && def.validate) {
funcKeywordCode(cxt, def)
} else if ("macro" in def) {
macroKeywordCode(cxt, def)
} else if (def.compile || def.validate) {
funcKeywordCode(cxt, def)
}
} | type AddedKeywordDefinition = KeywordDefinition & {
type: JSONType[]
schemaType: JSONType[]
} |
2,531 | function keywordCode(
it: SchemaObjCxt,
keyword: string,
def: AddedKeywordDefinition,
ruleType?: JSONType
): void {
const cxt = new KeywordCxt(it, def, keyword)
if ("code" in def) {
def.code(cxt, ruleType)
} else if (cxt.$data && def.validate) {
funcKeywordCode(cxt, def)
} else if ("macro" in def) {
macroKeywordCode(cxt, def)
} else if (def.compile || def.validate) {
funcKeywordCode(cxt, def)
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,532 | function keywordCode(
it: SchemaObjCxt,
keyword: string,
def: AddedKeywordDefinition,
ruleType?: JSONType
): void {
const cxt = new KeywordCxt(it, def, keyword)
if ("code" in def) {
def.code(cxt, ruleType)
} else if (cxt.$data && def.validate) {
funcKeywordCode(cxt, def)
} else if ("macro" in def) {
macroKeywordCode(cxt, def)
} else if (def.compile || def.validate) {
funcKeywordCode(cxt, def)
}
} | type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
? T | undefined
: T |
2,533 | function keywordCode(
it: SchemaObjCxt,
keyword: string,
def: AddedKeywordDefinition,
ruleType?: JSONType
): void {
const cxt = new KeywordCxt(it, def, keyword)
if ("code" in def) {
def.code(cxt, ruleType)
} else if (cxt.$data && def.validate) {
funcKeywordCode(cxt, def)
} else if ("macro" in def) {
macroKeywordCode(cxt, def)
} else if (def.compile || def.validate) {
funcKeywordCode(cxt, def)
}
} | type JSONType = (typeof _jsonTypes)[number] |
2,534 | function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
const {gen, keyword, schema, parentSchema, it} = cxt
const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
const schemaRef = useKeyword(gen, keyword, macroSchema)
if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)
const valid = gen.name("valid")
cxt.subschema(
{
schema: macroSchema,
schemaPath: nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true,
},
valid
)
cxt.pass(valid, () => cxt.error(true))
} | class KeywordCxt implements KeywordErrorCxt {
readonly gen: CodeGen
readonly allErrors?: boolean
readonly keyword: string
readonly data: Name // Name referencing the current level of the data instance
readonly $data?: string | false
schema: any // keyword value in the schema
readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
readonly parentSchema: AnySchemaObject
readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
// requires option trackErrors in keyword definition
params: KeywordCxtParams // object to pass parameters to error messages from keyword code
readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
readonly def: AddedKeywordDefinition
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
}
result(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.failResult(not(condition), successAction, failAction)
}
failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.gen.if(condition)
if (failAction) failAction()
else this.error()
if (successAction) {
this.gen.else()
successAction()
if (this.allErrors) this.gen.endIf()
} else {
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
}
pass(condition: Code, failAction?: () => void): void {
this.failResult(not(condition), undefined, failAction)
}
fail(condition?: Code): void {
if (condition === undefined) {
this.error()
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
return
}
this.gen.if(condition)
this.error()
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
fail$data(condition: Code): void {
if (!this.$data) return this.fail(condition)
const {schemaCode} = this
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
}
error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
if (errorParams) {
this.setParams(errorParams)
this._error(append, errorPaths)
this.setParams({})
return
}
this._error(append, errorPaths)
}
private _error(append?: boolean, errorPaths?: ErrorPaths): void {
;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
}
$dataError(): void {
reportError(this, this.def.$dataError || keyword$DataError)
}
reset(): void {
if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
resetErrorsCount(this.gen, this.errsCount)
}
ok(cond: Code | boolean): void {
if (!this.allErrors) this.gen.if(cond)
}
setParams(obj: KeywordCxtParams, assign?: true): void {
if (assign) Object.assign(this.params, obj)
else this.params = obj
}
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
}
check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
}
invalid$data(): Code {
const {gen, schemaCode, schemaType, def, it} = this
return or(wrong$DataType(), invalid$DataSchema())
function wrong$DataType(): Code {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
const st = Array.isArray(schemaType) ? schemaType : [schemaType]
return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
}
return nil
}
function invalid$DataSchema(): Code {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
return _`!${validateSchemaRef}(${schemaCode})`
}
return nil
}
}
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
}
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
const {it, gen} = this
if (!it.opts.unevaluated) return
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
}
}
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
}
} |
2,535 | function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
const {gen, keyword, schema, parentSchema, it} = cxt
const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
const schemaRef = useKeyword(gen, keyword, macroSchema)
if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)
const valid = gen.name("valid")
cxt.subschema(
{
schema: macroSchema,
schemaPath: nil,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
topSchemaRef: schemaRef,
compositeRule: true,
},
valid
)
cxt.pass(valid, () => cxt.error(true))
} | interface MacroKeywordDefinition extends FuncKeywordDefinition {
macro: MacroKeywordFunc
} |
2,536 | function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
const {gen, keyword, schema, parentSchema, $data, it} = cxt
checkAsyncKeyword(it, def)
const validate =
!$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
const validateRef = useKeyword(gen, keyword, validate)
const valid = gen.let("valid")
cxt.block$data(valid, validateKeyword)
cxt.ok(def.valid ?? valid)
function validateKeyword(): void {
if (def.errors === false) {
assignValid()
if (def.modifying) modifyData(cxt)
reportErrs(() => cxt.error())
} else {
const ruleErrs = def.async ? validateAsync() : validateSync()
if (def.modifying) modifyData(cxt)
reportErrs(() => addErrs(cxt, ruleErrs))
}
}
function validateAsync(): Name {
const ruleErrs = gen.let("ruleErrs", null)
gen.try(
() => assignValid(_`await `),
(e) =>
gen.assign(valid, false).if(
_`${e} instanceof ${it.ValidationError as Name}`,
() => gen.assign(ruleErrs, _`${e}.errors`),
() => gen.throw(e)
)
)
return ruleErrs
}
function validateSync(): Code {
const validateErrs = _`${validateRef}.errors`
gen.assign(validateErrs, null)
assignValid(nil)
return validateErrs
}
function assignValid(_await: Code = def.async ? _`await ` : nil): void {
const passCxt = it.opts.passContext ? N.this : N.self
const passSchema = !(("compile" in def && !$data) || def.schema === false)
gen.assign(
valid,
_`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
def.modifying
)
}
function reportErrs(errors: () => void): void {
gen.if(not(def.valid ?? valid), errors)
}
} | class KeywordCxt implements KeywordErrorCxt {
readonly gen: CodeGen
readonly allErrors?: boolean
readonly keyword: string
readonly data: Name // Name referencing the current level of the data instance
readonly $data?: string | false
schema: any // keyword value in the schema
readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
readonly parentSchema: AnySchemaObject
readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
// requires option trackErrors in keyword definition
params: KeywordCxtParams // object to pass parameters to error messages from keyword code
readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
readonly def: AddedKeywordDefinition
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
}
result(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.failResult(not(condition), successAction, failAction)
}
failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.gen.if(condition)
if (failAction) failAction()
else this.error()
if (successAction) {
this.gen.else()
successAction()
if (this.allErrors) this.gen.endIf()
} else {
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
}
pass(condition: Code, failAction?: () => void): void {
this.failResult(not(condition), undefined, failAction)
}
fail(condition?: Code): void {
if (condition === undefined) {
this.error()
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
return
}
this.gen.if(condition)
this.error()
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
fail$data(condition: Code): void {
if (!this.$data) return this.fail(condition)
const {schemaCode} = this
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
}
error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
if (errorParams) {
this.setParams(errorParams)
this._error(append, errorPaths)
this.setParams({})
return
}
this._error(append, errorPaths)
}
private _error(append?: boolean, errorPaths?: ErrorPaths): void {
;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
}
$dataError(): void {
reportError(this, this.def.$dataError || keyword$DataError)
}
reset(): void {
if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
resetErrorsCount(this.gen, this.errsCount)
}
ok(cond: Code | boolean): void {
if (!this.allErrors) this.gen.if(cond)
}
setParams(obj: KeywordCxtParams, assign?: true): void {
if (assign) Object.assign(this.params, obj)
else this.params = obj
}
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
}
check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
}
invalid$data(): Code {
const {gen, schemaCode, schemaType, def, it} = this
return or(wrong$DataType(), invalid$DataSchema())
function wrong$DataType(): Code {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
const st = Array.isArray(schemaType) ? schemaType : [schemaType]
return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
}
return nil
}
function invalid$DataSchema(): Code {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
return _`!${validateSchemaRef}(${schemaCode})`
}
return nil
}
}
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
}
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
const {it, gen} = this
if (!it.opts.unevaluated) return
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
}
}
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
}
} |
2,537 | function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
const {gen, keyword, schema, parentSchema, $data, it} = cxt
checkAsyncKeyword(it, def)
const validate =
!$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
const validateRef = useKeyword(gen, keyword, validate)
const valid = gen.let("valid")
cxt.block$data(valid, validateKeyword)
cxt.ok(def.valid ?? valid)
function validateKeyword(): void {
if (def.errors === false) {
assignValid()
if (def.modifying) modifyData(cxt)
reportErrs(() => cxt.error())
} else {
const ruleErrs = def.async ? validateAsync() : validateSync()
if (def.modifying) modifyData(cxt)
reportErrs(() => addErrs(cxt, ruleErrs))
}
}
function validateAsync(): Name {
const ruleErrs = gen.let("ruleErrs", null)
gen.try(
() => assignValid(_`await `),
(e) =>
gen.assign(valid, false).if(
_`${e} instanceof ${it.ValidationError as Name}`,
() => gen.assign(ruleErrs, _`${e}.errors`),
() => gen.throw(e)
)
)
return ruleErrs
}
function validateSync(): Code {
const validateErrs = _`${validateRef}.errors`
gen.assign(validateErrs, null)
assignValid(nil)
return validateErrs
}
function assignValid(_await: Code = def.async ? _`await ` : nil): void {
const passCxt = it.opts.passContext ? N.this : N.self
const passSchema = !(("compile" in def && !$data) || def.schema === false)
gen.assign(
valid,
_`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
def.modifying
)
}
function reportErrs(errors: () => void): void {
gen.if(not(def.valid ?? valid), errors)
}
} | interface FuncKeywordDefinition extends _KeywordDef {
validate?: SchemaValidateFunction | DataValidateFunction
compile?: CompileKeywordFunc
// schema: false makes validate not to expect schema (DataValidateFunction)
schema?: boolean // requires "validate"
modifying?: boolean
async?: boolean
valid?: boolean
errors?: boolean | "full"
} |
2,538 | function assignValid(_await: Code = def.async ? _`await ` : nil): void {
const passCxt = it.opts.passContext ? N.this : N.self
const passSchema = !(("compile" in def && !$data) || def.schema === false)
gen.assign(
valid,
_`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
def.modifying
)
} | type Code = _Code | Name |
2,539 | function modifyData(cxt: KeywordCxt): void {
const {gen, data, it} = cxt
gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))
} | class KeywordCxt implements KeywordErrorCxt {
readonly gen: CodeGen
readonly allErrors?: boolean
readonly keyword: string
readonly data: Name // Name referencing the current level of the data instance
readonly $data?: string | false
schema: any // keyword value in the schema
readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
readonly parentSchema: AnySchemaObject
readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
// requires option trackErrors in keyword definition
params: KeywordCxtParams // object to pass parameters to error messages from keyword code
readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
readonly def: AddedKeywordDefinition
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
}
result(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.failResult(not(condition), successAction, failAction)
}
failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.gen.if(condition)
if (failAction) failAction()
else this.error()
if (successAction) {
this.gen.else()
successAction()
if (this.allErrors) this.gen.endIf()
} else {
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
}
pass(condition: Code, failAction?: () => void): void {
this.failResult(not(condition), undefined, failAction)
}
fail(condition?: Code): void {
if (condition === undefined) {
this.error()
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
return
}
this.gen.if(condition)
this.error()
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
fail$data(condition: Code): void {
if (!this.$data) return this.fail(condition)
const {schemaCode} = this
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
}
error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
if (errorParams) {
this.setParams(errorParams)
this._error(append, errorPaths)
this.setParams({})
return
}
this._error(append, errorPaths)
}
private _error(append?: boolean, errorPaths?: ErrorPaths): void {
;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
}
$dataError(): void {
reportError(this, this.def.$dataError || keyword$DataError)
}
reset(): void {
if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
resetErrorsCount(this.gen, this.errsCount)
}
ok(cond: Code | boolean): void {
if (!this.allErrors) this.gen.if(cond)
}
setParams(obj: KeywordCxtParams, assign?: true): void {
if (assign) Object.assign(this.params, obj)
else this.params = obj
}
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
}
check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
}
invalid$data(): Code {
const {gen, schemaCode, schemaType, def, it} = this
return or(wrong$DataType(), invalid$DataSchema())
function wrong$DataType(): Code {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
const st = Array.isArray(schemaType) ? schemaType : [schemaType]
return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
}
return nil
}
function invalid$DataSchema(): Code {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
return _`!${validateSchemaRef}(${schemaCode})`
}
return nil
}
}
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
}
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
const {it, gen} = this
if (!it.opts.unevaluated) return
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
}
}
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
}
} |
2,540 | function addErrs(cxt: KeywordCxt, errs: Code): void {
const {gen} = cxt
gen.if(
_`Array.isArray(${errs})`,
() => {
gen
.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
.assign(N.errors, _`${N.vErrors}.length`)
extendErrors(cxt)
},
() => cxt.error()
)
} | class KeywordCxt implements KeywordErrorCxt {
readonly gen: CodeGen
readonly allErrors?: boolean
readonly keyword: string
readonly data: Name // Name referencing the current level of the data instance
readonly $data?: string | false
schema: any // keyword value in the schema
readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
readonly parentSchema: AnySchemaObject
readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
// requires option trackErrors in keyword definition
params: KeywordCxtParams // object to pass parameters to error messages from keyword code
readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
readonly def: AddedKeywordDefinition
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
validateKeywordUsage(it, def, keyword)
this.gen = it.gen
this.allErrors = it.allErrors
this.keyword = keyword
this.data = it.data
this.schema = it.schema[keyword]
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
this.schemaType = def.schemaType
this.parentSchema = it.schema
this.params = {}
this.it = it
this.def = def
if (this.$data) {
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
} else {
this.schemaCode = this.schemaValue
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
}
}
if ("code" in def ? def.trackErrors : def.errors !== false) {
this.errsCount = it.gen.const("_errs", N.errors)
}
}
result(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.failResult(not(condition), successAction, failAction)
}
failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
this.gen.if(condition)
if (failAction) failAction()
else this.error()
if (successAction) {
this.gen.else()
successAction()
if (this.allErrors) this.gen.endIf()
} else {
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
}
pass(condition: Code, failAction?: () => void): void {
this.failResult(not(condition), undefined, failAction)
}
fail(condition?: Code): void {
if (condition === undefined) {
this.error()
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
return
}
this.gen.if(condition)
this.error()
if (this.allErrors) this.gen.endIf()
else this.gen.else()
}
fail$data(condition: Code): void {
if (!this.$data) return this.fail(condition)
const {schemaCode} = this
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
}
error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
if (errorParams) {
this.setParams(errorParams)
this._error(append, errorPaths)
this.setParams({})
return
}
this._error(append, errorPaths)
}
private _error(append?: boolean, errorPaths?: ErrorPaths): void {
;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
}
$dataError(): void {
reportError(this, this.def.$dataError || keyword$DataError)
}
reset(): void {
if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
resetErrorsCount(this.gen, this.errsCount)
}
ok(cond: Code | boolean): void {
if (!this.allErrors) this.gen.if(cond)
}
setParams(obj: KeywordCxtParams, assign?: true): void {
if (assign) Object.assign(this.params, obj)
else this.params = obj
}
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
this.gen.block(() => {
this.check$data(valid, $dataValid)
codeBlock()
})
}
check$data(valid: Name = nil, $dataValid: Code = nil): void {
if (!this.$data) return
const {gen, schemaCode, schemaType, def} = this
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
if (valid !== nil) gen.assign(valid, true)
if (schemaType.length || def.validateSchema) {
gen.elseIf(this.invalid$data())
this.$dataError()
if (valid !== nil) gen.assign(valid, false)
}
gen.else()
}
invalid$data(): Code {
const {gen, schemaCode, schemaType, def, it} = this
return or(wrong$DataType(), invalid$DataSchema())
function wrong$DataType(): Code {
if (schemaType.length) {
/* istanbul ignore if */
if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
const st = Array.isArray(schemaType) ? schemaType : [schemaType]
return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
}
return nil
}
function invalid$DataSchema(): Code {
if (def.validateSchema) {
const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
return _`!${validateSchemaRef}(${schemaCode})`
}
return nil
}
}
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
const subschema = getSubschema(this.it, appl)
extendSubschemaData(subschema, this.it, appl)
extendSubschemaMode(subschema, appl)
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
subschemaCode(nextContext, valid)
return nextContext
}
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
const {it, gen} = this
if (!it.opts.unevaluated) return
if (it.props !== true && schemaCxt.props !== undefined) {
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
}
if (it.items !== true && schemaCxt.items !== undefined) {
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
}
}
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
const {it, gen} = this
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
return true
}
}
} |
2,541 | function addErrs(cxt: KeywordCxt, errs: Code): void {
const {gen} = cxt
gen.if(
_`Array.isArray(${errs})`,
() => {
gen
.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
.assign(N.errors, _`${N.vErrors}.length`)
extendErrors(cxt)
},
() => cxt.error()
)
} | type Code = _Code | Name |
2,542 | function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,543 | function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
} | interface FuncKeywordDefinition extends _KeywordDef {
validate?: SchemaValidateFunction | DataValidateFunction
compile?: CompileKeywordFunc
// schema: false makes validate not to expect schema (DataValidateFunction)
schema?: boolean // requires "validate"
modifying?: boolean
async?: boolean
valid?: boolean
errors?: boolean | "full"
} |
2,544 | function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
return gen.scopeValue(
"keyword",
typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
)
} | type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction |
2,545 | function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
return gen.scopeValue(
"keyword",
typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
)
} | class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly _constants: Constants = {}
private readonly opts: CGOptions
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
}
toString(): string {
return this._root.render(this.opts)
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
}
// `+=` code
add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode(new AnyCode(c))
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode(new If(condition))
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode(new If(condition))
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode(new Else())
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(If, Else)
}
private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: Code,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: Code,
forBody: (item: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode(new Label(label))
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node = new Return()
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Func)
}
optimize(n = 1): void {
while (n-- > 0) {
this._root.optimizeNodes()
this._root.optimizeNames(this._root.names, this._constants)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
}
private _elseNode(node: If | Else): CodeGen {
const n = this._currNode
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private get _root(): Root {
return this._nodes[0] as Root
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
// get nodeCount(): number {
// return this._root.count
// }
} |
2,546 | function validateKeywordUsage(
{schema, opts, self, errSchemaPath}: SchemaObjCxt,
def: AddedKeywordDefinition,
keyword: string
): void {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error")
}
const deps = def.dependencies
if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword])
if (!valid) {
const msg =
`keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors)
if (opts.validateSchema === "log") self.logger.error(msg)
else throw new Error(msg)
}
}
} | type AddedKeywordDefinition = KeywordDefinition & {
type: JSONType[]
schemaType: JSONType[]
} |
2,547 | function validateKeywordUsage(
{schema, opts, self, errSchemaPath}: SchemaObjCxt,
def: AddedKeywordDefinition,
keyword: string
): void {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error")
}
const deps = def.dependencies
if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
}
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword])
if (!valid) {
const msg =
`keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors)
if (opts.validateSchema === "log") self.logger.error(msg)
else throw new Error(msg)
}
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,548 | function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
const types = getJSONTypes(schema.type)
const hasNull = types.includes("null")
if (hasNull) {
if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
} else {
if (!types.length && schema.nullable !== undefined) {
throw new Error('"nullable" cannot be used without "type"')
}
if (schema.nullable === true) types.push("null")
}
return types
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,549 | function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
const {gen, data, opts} = it
const coerceTo = coerceToTypes(types, opts.coerceTypes)
const checkTypes =
types.length > 0 &&
!(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
gen.if(wrongType, () => {
if (coerceTo.length) coerceData(it, types, coerceTo)
else reportTypeError(it)
})
}
return checkTypes
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,550 | function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
const {gen, data, opts} = it
const dataType = gen.let("dataType", _`typeof ${data}`)
const coerced = gen.let("coerced", _`undefined`)
if (opts.coerceTypes === "array") {
gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
gen
.assign(data, _`${data}[0]`)
.assign(dataType, _`typeof ${data}`)
.if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
)
}
gen.if(_`${coerced} !== undefined`)
for (const t of coerceTo) {
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
coerceSpecificType(t)
}
}
gen.else()
reportTypeError(it)
gen.endIf()
gen.if(_`${coerced} !== undefined`, () => {
gen.assign(data, coerced)
assignParentData(it, coerced)
})
function coerceSpecificType(t: string): void {
switch (t) {
case "string":
gen
.elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
.assign(coerced, _`"" + ${data}`)
.elseIf(_`${data} === null`)
.assign(coerced, _`""`)
return
case "number":
gen
.elseIf(
_`${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`
)
.assign(coerced, _`+${data}`)
return
case "integer":
gen
.elseIf(
_`${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
)
.assign(coerced, _`+${data}`)
return
case "boolean":
gen
.elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
.assign(coerced, false)
.elseIf(_`${data} === "true" || ${data} === 1`)
.assign(coerced, true)
return
case "null":
gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
gen.assign(coerced, null)
return
case "array":
gen
.elseIf(
_`${dataType} === "string" || ${dataType} === "number"
|| ${dataType} === "boolean" || ${data} === null`
)
.assign(coerced, _`[${data}]`)
}
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,551 | function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
// TODO use gen.property
gen.if(_`${parentData} !== undefined`, () =>
gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,552 | function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
// TODO use gen.property
gen.if(_`${parentData} !== undefined`, () =>
gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
)
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,553 | function checkDataType(
dataType: JSONType,
data: Name,
strictNums?: boolean | "log",
correct = DataType.Correct
): Code {
const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
let cond: Code
switch (dataType) {
case "null":
return _`${data} ${EQ} null`
case "array":
cond = _`Array.isArray(${data})`
break
case "object":
cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
break
case "integer":
cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
break
case "number":
cond = numCond()
break
default:
return _`typeof ${data} ${EQ} ${dataType}`
}
return correct === DataType.Correct ? cond : not(cond)
function numCond(_cond: Code = nil): Code {
return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
}
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,554 | function checkDataType(
dataType: JSONType,
data: Name,
strictNums?: boolean | "log",
correct = DataType.Correct
): Code {
const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
let cond: Code
switch (dataType) {
case "null":
return _`${data} ${EQ} null`
case "array":
cond = _`Array.isArray(${data})`
break
case "object":
cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
break
case "integer":
cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
break
case "number":
cond = numCond()
break
default:
return _`typeof ${data} ${EQ} ${dataType}`
}
return correct === DataType.Correct ? cond : not(cond)
function numCond(_cond: Code = nil): Code {
return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
}
} | type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
? T | undefined
: T |
2,555 | function checkDataType(
dataType: JSONType,
data: Name,
strictNums?: boolean | "log",
correct = DataType.Correct
): Code {
const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
let cond: Code
switch (dataType) {
case "null":
return _`${data} ${EQ} null`
case "array":
cond = _`Array.isArray(${data})`
break
case "object":
cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
break
case "integer":
cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
break
case "number":
cond = numCond()
break
default:
return _`typeof ${data} ${EQ} ${dataType}`
}
return correct === DataType.Correct ? cond : not(cond)
function numCond(_cond: Code = nil): Code {
return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
}
} | type JSONType = (typeof _jsonTypes)[number] |
2,556 | function numCond(_cond: Code = nil): Code {
return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
} | type Code = _Code | Name |
2,557 | function reportTypeError(it: SchemaObjCxt): void {
const cxt = getTypeErrorContext(it)
reportError(cxt, typeError)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,558 | function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
const {gen, data, schema} = it
const schemaCode = schemaRefOrVal(it, schema, "type")
return {
gen,
keyword: "type",
data,
schema: schema.type,
schemaCode,
schemaValue: schemaCode,
parentSchema: schema,
params: {},
it,
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,559 | function getSubschema(
it: SchemaObjCxt,
{keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
): SubschemaContext {
if (keyword !== undefined && schema !== undefined) {
throw new Error('both "keyword" and "schema" passed, only one allowed')
}
if (keyword !== undefined) {
const sch = it.schema[keyword]
return schemaProp === undefined
? {
schema: sch,
schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
}
: {
schema: sch[schemaProp],
schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
}
}
if (schema !== undefined) {
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath,
}
}
throw new Error('either "keyword" or "schema" must be passed')
} | type SubschemaArgs = Partial<{
keyword: string
schemaProp: string | number
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef: Code
data: Name | Code
dataProp: Code | string | number
dataTypes: JSONType[]
definedProperties: Set<string>
propertyName: Name
dataPropType: Type
jtdDiscriminator: string
jtdMetadata: boolean
compositeRule: true
createErrors: boolean
allErrors: boolean
}> |
2,560 | function getSubschema(
it: SchemaObjCxt,
{keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
): SubschemaContext {
if (keyword !== undefined && schema !== undefined) {
throw new Error('both "keyword" and "schema" passed, only one allowed')
}
if (keyword !== undefined) {
const sch = it.schema[keyword]
return schemaProp === undefined
? {
schema: sch,
schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
}
: {
schema: sch[schemaProp],
schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
}
}
if (schema !== undefined) {
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
}
return {
schema,
schemaPath,
topSchemaRef,
errSchemaPath,
}
}
throw new Error('either "keyword" or "schema" must be passed')
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,561 | function extendSubschemaData(
subschema: SubschemaContext,
it: SchemaObjCxt,
{dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed')
}
const {gen} = it
if (dataProp !== undefined) {
const {errorPath, dataPathArr, opts} = it
const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
dataContextProps(nextData)
subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
subschema.parentDataProperty = _`${dataProp}`
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
}
if (data !== undefined) {
const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
dataContextProps(nextData)
if (propertyName !== undefined) subschema.propertyName = propertyName
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes) subschema.dataTypes = dataTypes
function dataContextProps(_nextData: Name): void {
subschema.data = _nextData
subschema.dataLevel = it.dataLevel + 1
subschema.dataTypes = []
it.definedProperties = new Set<string>()
subschema.parentData = it.data
subschema.dataNames = [...it.dataNames, _nextData]
}
} | type SubschemaArgs = Partial<{
keyword: string
schemaProp: string | number
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef: Code
data: Name | Code
dataProp: Code | string | number
dataTypes: JSONType[]
definedProperties: Set<string>
propertyName: Name
dataPropType: Type
jtdDiscriminator: string
jtdMetadata: boolean
compositeRule: true
createErrors: boolean
allErrors: boolean
}> |
2,562 | function extendSubschemaData(
subschema: SubschemaContext,
it: SchemaObjCxt,
{dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed')
}
const {gen} = it
if (dataProp !== undefined) {
const {errorPath, dataPathArr, opts} = it
const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
dataContextProps(nextData)
subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
subschema.parentDataProperty = _`${dataProp}`
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
}
if (data !== undefined) {
const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
dataContextProps(nextData)
if (propertyName !== undefined) subschema.propertyName = propertyName
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes) subschema.dataTypes = dataTypes
function dataContextProps(_nextData: Name): void {
subschema.data = _nextData
subschema.dataLevel = it.dataLevel + 1
subschema.dataTypes = []
it.definedProperties = new Set<string>()
subschema.parentData = it.data
subschema.dataNames = [...it.dataNames, _nextData]
}
} | interface SubschemaContext {
// TODO use Optional? align with SchemCxt property types
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef?: Code
errorPath?: Code
dataLevel?: number
dataTypes?: JSONType[]
data?: Name
parentData?: Name
parentDataProperty?: Code | number
dataNames?: Name[]
dataPathArr?: (Code | number)[]
propertyName?: Name
jtdDiscriminator?: string
jtdMetadata?: boolean
compositeRule?: true
createErrors?: boolean
allErrors?: boolean
} |
2,563 | function extendSubschemaData(
subschema: SubschemaContext,
it: SchemaObjCxt,
{dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
if (data !== undefined && dataProp !== undefined) {
throw new Error('both "data" and "dataProp" passed, only one allowed')
}
const {gen} = it
if (dataProp !== undefined) {
const {errorPath, dataPathArr, opts} = it
const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
dataContextProps(nextData)
subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
subschema.parentDataProperty = _`${dataProp}`
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
}
if (data !== undefined) {
const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
dataContextProps(nextData)
if (propertyName !== undefined) subschema.propertyName = propertyName
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
}
if (dataTypes) subschema.dataTypes = dataTypes
function dataContextProps(_nextData: Name): void {
subschema.data = _nextData
subschema.dataLevel = it.dataLevel + 1
subschema.dataTypes = []
it.definedProperties = new Set<string>()
subschema.parentData = it.data
subschema.dataNames = [...it.dataNames, _nextData]
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,564 | function dataContextProps(_nextData: Name): void {
subschema.data = _nextData
subschema.dataLevel = it.dataLevel + 1
subschema.dataTypes = []
it.definedProperties = new Set<string>()
subschema.parentData = it.data
subschema.dataNames = [...it.dataNames, _nextData]
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,565 | function extendSubschemaMode(
subschema: SubschemaContext,
{jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
): void {
if (compositeRule !== undefined) subschema.compositeRule = compositeRule
if (createErrors !== undefined) subschema.createErrors = createErrors
if (allErrors !== undefined) subschema.allErrors = allErrors
subschema.jtdDiscriminator = jtdDiscriminator // not inherited
subschema.jtdMetadata = jtdMetadata // not inherited
} | type SubschemaArgs = Partial<{
keyword: string
schemaProp: string | number
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef: Code
data: Name | Code
dataProp: Code | string | number
dataTypes: JSONType[]
definedProperties: Set<string>
propertyName: Name
dataPropType: Type
jtdDiscriminator: string
jtdMetadata: boolean
compositeRule: true
createErrors: boolean
allErrors: boolean
}> |
2,566 | function extendSubschemaMode(
subschema: SubschemaContext,
{jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
): void {
if (compositeRule !== undefined) subschema.compositeRule = compositeRule
if (createErrors !== undefined) subschema.createErrors = createErrors
if (allErrors !== undefined) subschema.allErrors = allErrors
subschema.jtdDiscriminator = jtdDiscriminator // not inherited
subschema.jtdMetadata = jtdMetadata // not inherited
} | interface SubschemaContext {
// TODO use Optional? align with SchemCxt property types
schema: AnySchema
schemaPath: Code
errSchemaPath: string
topSchemaRef?: Code
errorPath?: Code
dataLevel?: number
dataTypes?: JSONType[]
data?: Name
parentData?: Name
parentDataProperty?: Code | number
dataNames?: Name[]
dataPathArr?: (Code | number)[]
propertyName?: Name
jtdDiscriminator?: string
jtdMetadata?: boolean
compositeRule?: true
createErrors?: boolean
allErrors?: boolean
} |
2,567 | function assignDefaults(it: SchemaObjCxt, ty?: string): void {
const {properties, items} = it.schema
if (ty === "object" && properties) {
for (const key in properties) {
assignDefault(it, key, properties[key].default)
}
} else if (ty === "array" && Array.isArray(items)) {
items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,568 | function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
const {gen, compositeRule, data, opts} = it
if (defaultValue === undefined) return
const childData = _`${data}${getProperty(prop)}`
if (compositeRule) {
checkStrictMode(it, `default is ignored for: ${childData}`)
return
}
let condition = _`${childData} === undefined`
if (opts.useDefaults === "empty") {
condition = _`${condition} || ${childData} === null || ${childData} === ""`
}
// `${childData} === undefined` +
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,569 | function schemaHasRulesForType(
{schema, self}: SchemaObjCxt,
type: JSONType
): boolean | undefined {
const group = self.RULES.types[type]
return group && group !== true && shouldUseGroup(schema, group)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,570 | function schemaHasRulesForType(
{schema, self}: SchemaObjCxt,
type: JSONType
): boolean | undefined {
const group = self.RULES.types[type]
return group && group !== true && shouldUseGroup(schema, group)
} | type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
? T | undefined
: T |
2,571 | function schemaHasRulesForType(
{schema, self}: SchemaObjCxt,
type: JSONType
): boolean | undefined {
const group = self.RULES.types[type]
return group && group !== true && shouldUseGroup(schema, group)
} | type JSONType = (typeof _jsonTypes)[number] |
2,572 | function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
return group.rules.some((rule) => shouldUseRule(schema, rule))
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,573 | function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
return group.rules.some((rule) => shouldUseRule(schema, rule))
} | interface RuleGroup {
type?: JSONType
rules: Rule[]
} |
2,574 | function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
return (
schema[rule.keyword] !== undefined ||
rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
)
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,575 | function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
return (
schema[rule.keyword] !== undefined ||
rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
)
} | interface Rule {
keyword: string
definition: AddedKeywordDefinition
} |
2,576 | (cxt: ParseCxt) => void | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,577 | function compileParser(
this: Ajv,
sch: SchemaEnv,
definitions: SchemaObjectMap
): SchemaEnv {
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
const parseName = gen.scopeName("parse")
const cxt: ParseCxt = {
self: this,
gen,
schema: sch.schema as SchemaObject,
schemaEnv: sch,
definitions,
data: N.data,
parseName,
char: gen.name("c"),
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
sch.parseName = parseName
parserFunction(cxt)
gen.optimize(this.opts.code.optimize)
const parseFuncCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
const makeParse = new Function(`${N.scope}`, sourceCode)
const parse: (json: string) => unknown = makeParse(this.scope.get())
this.scope.value(parseName, {ref: parse})
sch.parse = parse
} catch (e) {
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
delete sch.parse
delete sch.parseName
throw e
} finally {
this._compilations.delete(sch)
}
return sch
} | class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema
readonly schemaId?: "$id" | "id"
readonly root: SchemaEnv
baseId: string // TODO possibly, it should be readonly
schemaPath?: string
localRefs?: LocalRefs
readonly meta?: boolean
readonly $async?: boolean // true if the current schema is asynchronous.
readonly refs: SchemaRefs = {}
readonly dynamicAnchors: {[Ref in string]?: true} = {}
validate?: AnyValidateFunction
validateName?: ValueScopeName
serialize?: (data: unknown) => string
serializeName?: ValueScopeName
parse?: (data: string) => unknown
parseName?: ValueScopeName
constructor(env: SchemaEnvArgs) {
let schema: AnySchemaObject | undefined
if (typeof env.schema == "object") schema = env.schema
this.schema = env.schema
this.schemaId = env.schemaId
this.root = env.root || this
this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
this.schemaPath = env.schemaPath
this.localRefs = env.localRefs
this.meta = env.meta
this.$async = schema?.$async
this.refs = {}
}
} |
2,578 | function compileParser(
this: Ajv,
sch: SchemaEnv,
definitions: SchemaObjectMap
): SchemaEnv {
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
const parseName = gen.scopeName("parse")
const cxt: ParseCxt = {
self: this,
gen,
schema: sch.schema as SchemaObject,
schemaEnv: sch,
definitions,
data: N.data,
parseName,
char: gen.name("c"),
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
sch.parseName = parseName
parserFunction(cxt)
gen.optimize(this.opts.code.optimize)
const parseFuncCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
const makeParse = new Function(`${N.scope}`, sourceCode)
const parse: (json: string) => unknown = makeParse(this.scope.get())
this.scope.value(parseName, {ref: parse})
sch.parse = parse
} catch (e) {
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
delete sch.parse
delete sch.parseName
throw e
} finally {
this._compilations.delete(sch)
}
return sch
} | class Ajv {
opts: InstanceOptions
errors?: ErrorObject[] | null // errors from the last validation
logger: Logger
// shared external scope values for compiled functions
readonly scope: ValueScope
readonly schemas: {[Key in string]?: SchemaEnv} = {}
readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
readonly formats: {[Name in string]?: AddedFormat} = {}
readonly RULES: ValidationRules
readonly _compilations: Set<SchemaEnv> = new Set()
private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
private readonly _metaOpts: InstanceOptions
static ValidationError = ValidationError
static MissingRefError = MissingRefError
constructor(opts: Options = {}) {
opts = this.opts = {...opts, ...requiredOptions(opts)}
const {es5, lines} = this.opts.code
this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
this.logger = getLogger(opts.logger)
const formatOpt = opts.validateFormats
opts.validateFormats = false
this.RULES = getRules()
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
this._metaOpts = getMetaSchemaOptions.call(this)
if (opts.formats) addInitialFormats.call(this)
this._addVocabularies()
this._addDefaultMetaSchema()
if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
addInitialSchemas.call(this)
opts.validateFormats = formatOpt
}
_addVocabularies(): void {
this.addKeyword("$async")
}
_addDefaultMetaSchema(): void {
const {$data, meta, schemaId} = this.opts
let _dataRefSchema: SchemaObject = $dataRefSchema
if (schemaId === "id") {
_dataRefSchema = {...$dataRefSchema}
_dataRefSchema.id = _dataRefSchema.$id
delete _dataRefSchema.$id
}
if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
}
defaultMeta(): string | AnySchemaObject | undefined {
const {meta, schemaId} = this.opts
return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
}
// Validate data using schema
// AnySchema will be compiled and cached using schema itself as a key for Map
validate(schema: Schema | string, data: unknown): boolean
validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
// Separated for type inference to work
// eslint-disable-next-line @typescript-eslint/unified-signatures
validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
// This overload is only intended for typescript inference, the first
// argument prevents manual type annotation from matching this overload
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
validate<T>(
schemaKeyRef: AnySchema | string, // key, ref or schema object
data: unknown | T // to be validated
): boolean | Promise<T> {
let v: AnyValidateFunction | undefined
if (typeof schemaKeyRef == "string") {
v = this.getSchema<T>(schemaKeyRef)
if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
} else {
v = this.compile<T>(schemaKeyRef)
}
const valid = v(data)
if (!("$async" in v)) this.errors = v.errors
return valid
}
// Create validation function for passed schema
// _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
// Separated for type inference to work
// eslint-disable-next-line @typescript-eslint/unified-signatures
compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
// This overload is only intended for typescript inference, the first
// argument prevents manual type annotation from matching this overload
compile<N extends never, T extends SomeJTDSchemaType>(
schema: T,
_meta?: boolean
): ValidateFunction<JTDDataType<T>>
compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
const sch = this._addSchema(schema, _meta)
return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
}
// Creates validating function for passed schema with asynchronous loading of missing schemas.
// `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
// TODO allow passing schema URI
// meta - optional true to compile meta-schema
compileAsync<T = unknown>(
schema: SchemaObject | JSONSchemaType<T>,
_meta?: boolean
): Promise<ValidateFunction<T>>
// Separated for type inference to work
// eslint-disable-next-line @typescript-eslint/unified-signatures
compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
// eslint-disable-next-line @typescript-eslint/unified-signatures
compileAsync<T = unknown>(
schema: AnySchemaObject,
meta?: boolean
): Promise<AnyValidateFunction<T>>
compileAsync<T = unknown>(
schema: AnySchemaObject,
meta?: boolean
): Promise<AnyValidateFunction<T>> {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function")
}
const {loadSchema} = this.opts
return runCompileAsync.call(this, schema, meta)
async function runCompileAsync(
this: Ajv,
_schema: AnySchemaObject,
_meta?: boolean
): Promise<AnyValidateFunction> {
await loadMetaSchema.call(this, _schema.$schema)
const sch = this._addSchema(_schema, _meta)
return sch.validate || _compileAsync.call(this, sch)
}
async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, {$ref}, true)
}
}
async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
try {
return this._compileSchemaEnv(sch)
} catch (e) {
if (!(e instanceof MissingRefError)) throw e
checkLoaded.call(this, e)
await loadMissingSchema.call(this, e.missingSchema)
return _compileAsync.call(this, sch)
}
}
function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
}
}
async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
const _schema = await _loadSchema.call(this, ref)
if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
}
async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
const p = this._loading[ref]
if (p) return p
try {
return await (this._loading[ref] = loadSchema(ref))
} finally {
delete this._loading[ref]
}
}
}
// Adds schema to the instance
addSchema(
schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
_meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
): Ajv {
if (Array.isArray(schema)) {
for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
return this
}
let id: string | undefined
if (typeof schema === "object") {
const {schemaId} = this.opts
id = schema[schemaId]
if (id !== undefined && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`)
}
}
key = normalizeId(key || id)
this._checkUnique(key)
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
return this
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(
schema: AnySchemaObject,
key?: string, // schema key
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
): Ajv {
this.addSchema(schema, key, true, _validateSchema)
return this
}
// Validate schema against its meta-schema
validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
if (typeof schema == "boolean") return true
let $schema: string | AnySchemaObject | undefined
$schema = schema.$schema
if ($schema !== undefined && typeof $schema != "string") {
throw new Error("$schema must be a string")
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta()
if (!$schema) {
this.logger.warn("meta-schema not available")
this.errors = null
return true
}
const valid = this.validate($schema, schema)
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText()
if (this.opts.validateSchema === "log") this.logger.error(message)
else throw new Error(message)
}
return valid
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
let sch
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
if (sch === undefined) {
const {schemaId} = this.opts
const root = new SchemaEnv({schema: {}, schemaId})
sch = resolveSchema.call(this, root, keyRef)
if (!sch) return
this.refs[keyRef] = sch
}
return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef)
this._removeAllSchemas(this.refs, schemaKeyRef)
return this
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas)
this._removeAllSchemas(this.refs)
this._cache.clear()
return this
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef)
if (typeof sch == "object") this._cache.delete(sch.schema)
delete this.schemas[schemaKeyRef]
delete this.refs[schemaKeyRef]
return this
}
case "object": {
const cacheKey = schemaKeyRef
this._cache.delete(cacheKey)
let id = schemaKeyRef[this.opts.schemaId]
if (id) {
id = normalizeId(id)
delete this.schemas[id]
delete this.refs[id]
}
return this
}
default:
throw new Error("ajv.removeSchema: invalid parameter")
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions: Vocabulary): Ajv {
for (const def of definitions) this.addKeyword(def)
return this
}
addKeyword(
kwdOrDef: string | KeywordDefinition,
def?: KeywordDefinition // deprecated
): Ajv {
let keyword: string | string[]
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword")
def.keyword = keyword
}
} else if (typeof kwdOrDef == "object" && def === undefined) {
def = kwdOrDef
keyword = def.keyword
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array")
}
} else {
throw new Error("invalid addKeywords parameters")
}
checkKeyword.call(this, keyword, def)
if (!def) {
eachItem(keyword, (kwd) => addRule.call(this, kwd))
return this
}
keywordMetaschema.call(this, def)
const definition: AddedKeywordDefinition = {
...def,
type: getJSONTypes(def.type),
schemaType: getJSONTypes(def.schemaType),
}
eachItem(
keyword,
definition.type.length === 0
? (k) => addRule.call(this, k, definition)
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
)
return this
}
getKeyword(keyword: string): AddedKeywordDefinition | boolean {
const rule = this.RULES.all[keyword]
return typeof rule == "object" ? rule.definition : !!rule
}
// Remove keyword
removeKeyword(keyword: string): Ajv {
// TODO return type should be Ajv
const {RULES} = this
delete RULES.keywords[keyword]
delete RULES.all[keyword]
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword)
if (i >= 0) group.rules.splice(i, 1)
}
return this
}
// Add format
addFormat(name: string, format: Format): Ajv {
if (typeof format == "string") format = new RegExp(format)
this.formats[name] = format
return this
}
errorsText(
errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
{separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
): string {
if (!errors || errors.length === 0) return "No errors"
return errors
.map((e) => `${dataVar}${e.instancePath} ${e.message}`)
.reduce((text, msg) => text + separator + msg)
}
$dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
const rules = this.RULES.all
metaSchema = JSON.parse(JSON.stringify(metaSchema))
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
let keywords = metaSchema
for (const seg of segments) keywords = keywords[seg] as AnySchemaObject
for (const key in rules) {
const rule = rules[key]
if (typeof rule != "object") continue
const {$data} = rule.definition
const schema = keywords[key] as AnySchemaObject | undefined
if ($data && schema) keywords[key] = schemaOrData(schema)
}
}
return metaSchema
}
private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
for (const keyRef in schemas) {
const sch = schemas[keyRef]
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef]
} else if (sch && !sch.meta) {
this._cache.delete(sch.schema)
delete schemas[keyRef]
}
}
}
}
_addSchema(
schema: AnySchema,
meta?: boolean,
baseId?: string,
validateSchema = this.opts.validateSchema,
addSchema = this.opts.addUsedSchema
): SchemaEnv {
let id: string | undefined
const {schemaId} = this.opts
if (typeof schema == "object") {
id = schema[schemaId]
} else {
if (this.opts.jtd) throw new Error("schema must be object")
else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
}
let sch = this._cache.get(schema)
if (sch !== undefined) return sch
baseId = normalizeId(id || baseId)
const localRefs = getSchemaRefs.call(this, schema, baseId)
sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
this._cache.set(sch.schema, sch)
if (addSchema && !baseId.startsWith("#")) {
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
if (baseId) this._checkUnique(baseId)
this.refs[baseId] = sch
}
if (validateSchema) this.validateSchema(schema, true)
return sch
}
private _checkUnique(id: string): void {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`)
}
}
private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
if (sch.meta) this._compileMetaSchema(sch)
else compileSchema.call(this, sch)
/* istanbul ignore if */
if (!sch.validate) throw new Error("ajv implementation error")
return sch.validate
}
private _compileMetaSchema(sch: SchemaEnv): void {
const currentOpts = this.opts
this.opts = this._metaOpts
try {
compileSchema.call(this, sch)
} finally {
this.opts = currentOpts
}
}
} |
2,579 | function compileParser(
this: Ajv,
sch: SchemaEnv,
definitions: SchemaObjectMap
): SchemaEnv {
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
const parseName = gen.scopeName("parse")
const cxt: ParseCxt = {
self: this,
gen,
schema: sch.schema as SchemaObject,
schemaEnv: sch,
definitions,
data: N.data,
parseName,
char: gen.name("c"),
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
sch.parseName = parseName
parserFunction(cxt)
gen.optimize(this.opts.code.optimize)
const parseFuncCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
const makeParse = new Function(`${N.scope}`, sourceCode)
const parse: (json: string) => unknown = makeParse(this.scope.get())
this.scope.value(parseName, {ref: parse})
sch.parse = parse
} catch (e) {
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
delete sch.parse
delete sch.parseName
throw e
} finally {
this._compilations.delete(sch)
}
return sch
} | class Ajv extends AjvCore {
constructor(opts: JTDOptions = {}) {
super({
...opts,
jtd: true,
})
}
_addVocabularies(): void {
super._addVocabularies()
this.addVocabulary(jtdVocabulary)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false)
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string
// Separated for type inference to work
// eslint-disable-next-line @typescript-eslint/unified-signatures
compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string
compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string {
const sch = this._addSchema(schema)
return sch.serialize || this._compileSerializer(sch)
}
compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>
// Separated for type inference to work
// eslint-disable-next-line @typescript-eslint/unified-signatures
compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>
compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> {
const sch = this._addSchema(schema)
return (sch.parse || this._compileParser(sch)) as JTDParser<T>
}
private _compileSerializer<T>(sch: SchemaEnv): (data: T) => string {
compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
/* istanbul ignore if */
if (!sch.serialize) throw new Error("ajv implementation error")
return sch.serialize
}
private _compileParser(sch: SchemaEnv): JTDParser {
compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
/* istanbul ignore if */
if (!sch.parse) throw new Error("ajv implementation error")
return sch.parse
}
} |
2,580 | function compileParser(
this: Ajv,
sch: SchemaEnv,
definitions: SchemaObjectMap
): SchemaEnv {
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
const parseName = gen.scopeName("parse")
const cxt: ParseCxt = {
self: this,
gen,
schema: sch.schema as SchemaObject,
schemaEnv: sch,
definitions,
data: N.data,
parseName,
char: gen.name("c"),
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
sch.parseName = parseName
parserFunction(cxt)
gen.optimize(this.opts.code.optimize)
const parseFuncCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
const makeParse = new Function(`${N.scope}`, sourceCode)
const parse: (json: string) => unknown = makeParse(this.scope.get())
this.scope.value(parseName, {ref: parse})
sch.parse = parse
} catch (e) {
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
delete sch.parse
delete sch.parseName
throw e
} finally {
this._compilations.delete(sch)
}
return sch
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,581 | function compileParser(
this: Ajv,
sch: SchemaEnv,
definitions: SchemaObjectMap
): SchemaEnv {
const _sch = getCompilingSchema.call(this, sch)
if (_sch) return _sch
const {es5, lines} = this.opts.code
const {ownProperties} = this.opts
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
const parseName = gen.scopeName("parse")
const cxt: ParseCxt = {
self: this,
gen,
schema: sch.schema as SchemaObject,
schemaEnv: sch,
definitions,
data: N.data,
parseName,
char: gen.name("c"),
}
let sourceCode: string | undefined
try {
this._compilations.add(sch)
sch.parseName = parseName
parserFunction(cxt)
gen.optimize(this.opts.code.optimize)
const parseFuncCode = gen.toString()
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
const makeParse = new Function(`${N.scope}`, sourceCode)
const parse: (json: string) => unknown = makeParse(this.scope.get())
this.scope.value(parseName, {ref: parse})
sch.parse = parse
} catch (e) {
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
delete sch.parse
delete sch.parseName
throw e
} finally {
this._compilations.delete(sch)
}
return sch
} | type SchemaObjectMap = {[Ref in string]?: SchemaObject} |
2,582 | function parserFunction(cxt: ParseCxt): void {
const {gen, parseName, char} = cxt
gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => {
gen.let(N.data)
gen.let(char)
gen.assign(_`${parseName}.message`, undef)
gen.assign(_`${parseName}.position`, undef)
gen.assign(N.jsonPos, _`${N.jsonPos} || 0`)
gen.const(N.jsonLen, _`${N.json}.length`)
parseCode(cxt)
skipWhitespace(cxt)
gen.if(N.jsonPart, () => {
gen.assign(_`${parseName}.position`, N.jsonPos)
gen.return(N.data)
})
gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data))
jsonSyntaxError(cxt)
})
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,583 | function parseCode(cxt: ParseCxt): void {
let form: JTDForm | undefined
for (const key of jtdForms) {
if (key in cxt.schema) {
form = key
break
}
}
if (form) parseNullable(cxt, genParse[form])
else parseEmpty(cxt)
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,584 | function parseNullable(cxt: ParseCxt, parseForm: GenParse): void {
const {gen, schema, data} = cxt
if (!schema.nullable) return parseForm(cxt)
tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null))
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,585 | function parseNullable(cxt: ParseCxt, parseForm: GenParse): void {
const {gen, schema, data} = cxt
if (!schema.nullable) return parseForm(cxt)
tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null))
} | type GenParse = (cxt: ParseCxt) => void |
2,586 | function parseElements(cxt: ParseCxt): void {
const {gen, schema, data} = cxt
parseToken(cxt, "[")
const ix = gen.let("i", 0)
gen.assign(data, _`[]`)
parseItems(cxt, "]", () => {
const el = gen.let("el")
parseCode({...cxt, schema: schema.elements, data: el})
gen.assign(_`${data}[${ix}++]`, el)
})
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,587 | function parseValues(cxt: ParseCxt): void {
const {gen, schema, data} = cxt
parseToken(cxt, "{")
gen.assign(data, _`{}`)
parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values))
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,588 | function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
tryParseItems(cxt, endToken, block)
parseToken(cxt, endToken)
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,589 | function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
const {gen} = cxt
gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
block()
tryParseToken(cxt, ",", () => gen.break(), hasItem)
})
function hasItem(): void {
tryParseToken(cxt, endToken, () => {}, jsonSyntaxError)
}
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,590 | function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void {
const {gen} = cxt
const key = gen.let("key")
parseString({...cxt, data: key})
parseToken(cxt, ":")
parsePropertyValue(cxt, key, schema)
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,591 | function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void {
const {gen} = cxt
const key = gen.let("key")
parseString({...cxt, data: key})
parseToken(cxt, ":")
parsePropertyValue(cxt, key, schema)
} | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,592 | function parseDiscriminator(cxt: ParseCxt): void {
const {gen, data, schema} = cxt
const {discriminator, mapping} = schema
parseToken(cxt, "{")
gen.assign(data, _`{}`)
const startPos = gen.const("pos", N.jsonPos)
const value = gen.let("value")
const tag = gen.let("tag")
tryParseItems(cxt, "}", () => {
const key = gen.let("key")
parseString({...cxt, data: key})
parseToken(cxt, ":")
gen.if(
_`${key} === ${discriminator}`,
() => {
parseString({...cxt, data: tag})
gen.assign(_`${data}[${key}]`, tag)
gen.break()
},
() => parseEmpty({...cxt, data: value}) // can be discarded/skipped
)
})
gen.assign(N.jsonPos, startPos)
gen.if(_`${tag} === undefined`)
parsingError(cxt, str`discriminator tag not found`)
for (const tagValue in mapping) {
gen.elseIf(_`${tag} === ${tagValue}`)
parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator)
}
gen.else()
parsingError(cxt, str`discriminator value not in schema`)
gen.endIf()
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,593 | function parseProperties(cxt: ParseCxt): void {
const {gen, data} = cxt
parseToken(cxt, "{")
gen.assign(data, _`{}`)
parseSchemaProperties(cxt)
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,594 | function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void {
const {gen, schema, data} = cxt
const {properties, optionalProperties, additionalProperties} = schema
parseItems(cxt, "}", () => {
const key = gen.let("key")
parseString({...cxt, data: key})
parseToken(cxt, ":")
gen.if(false)
parseDefinedProperty(cxt, key, properties)
parseDefinedProperty(cxt, key, optionalProperties)
if (discriminator) {
gen.elseIf(_`${key} === ${discriminator}`)
const tag = gen.let("tag")
parseString({...cxt, data: tag}) // can be discarded, it is already assigned
}
gen.else()
if (additionalProperties) {
parseEmpty({...cxt, data: _`${data}[${key}]`})
} else {
parsingError(cxt, str`property ${key} not allowed`)
}
gen.endIf()
})
if (properties) {
const hasProp = hasPropFunc(gen)
const allProps: Code = and(
...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`)
)
gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`))
}
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,595 | function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
const {gen} = cxt
for (const prop in schemas) {
gen.elseIf(_`${key} === ${prop}`)
parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
}
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,596 | function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
const {gen} = cxt
for (const prop in schemas) {
gen.elseIf(_`${key} === ${prop}`)
parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
}
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,597 | function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
const {gen} = cxt
for (const prop in schemas) {
gen.elseIf(_`${key} === ${prop}`)
parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
}
} | type SchemaObjectMap = {[Ref in string]?: SchemaObject} |
2,598 | function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void {
parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`})
} | interface ParseCxt {
readonly gen: CodeGen
readonly self: Ajv // current Ajv instance
readonly schemaEnv: SchemaEnv
readonly definitions: SchemaObjectMap
schema: SchemaObject
data: Code
parseName: Name
char: Name
} |
2,599 | function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void {
parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`})
} | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.