id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,400 | function resolve(
this: Ajv,
root: SchemaEnv, // information about the root schema for the current schema
ref: string // reference to resolve
): SchemaEnv | undefined {
let sch
while (typeof (sch = this.refs[ref]) == "string") ref = sch
return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
} | 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,401 | function resolveSchema(
this: Ajv,
root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string // reference to resolve
): SchemaEnv | undefined {
const p = this.opts.uriResolver.parse(ref)
const refPath = _getFullPath(this.opts.uriResolver, p)
let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
}
const id = normalizeId(refPath)
const schOrRef = this.refs[id] || this.schemas[id]
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef)
if (typeof sch?.schema !== "object") return
return getJsonPointer.call(this, p, sch)
}
if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) {
const {schema} = schOrRef
const {schemaId} = this.opts
const schId = schema[schemaId]
if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
return new SchemaEnv({schema, schemaId, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
} | 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,402 | function resolveSchema(
this: Ajv,
root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string // reference to resolve
): SchemaEnv | undefined {
const p = this.opts.uriResolver.parse(ref)
const refPath = _getFullPath(this.opts.uriResolver, p)
let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
}
const id = normalizeId(refPath)
const schOrRef = this.refs[id] || this.schemas[id]
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef)
if (typeof sch?.schema !== "object") return
return getJsonPointer.call(this, p, sch)
}
if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) {
const {schema} = schOrRef
const {schemaId} = this.opts
const schId = schema[schemaId]
if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
return new SchemaEnv({schema, schemaId, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
} | 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,403 | function resolveSchema(
this: Ajv,
root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string // reference to resolve
): SchemaEnv | undefined {
const p = this.opts.uriResolver.parse(ref)
const refPath = _getFullPath(this.opts.uriResolver, p)
let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
}
const id = normalizeId(refPath)
const schOrRef = this.refs[id] || this.schemas[id]
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef)
if (typeof sch?.schema !== "object") return
return getJsonPointer.call(this, p, sch)
}
if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) {
const {schema} = schOrRef
const {schemaId} = this.opts
const schId = schema[schemaId]
if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
return new SchemaEnv({schema, schemaId, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
} | 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,404 | function resolveSchema(
this: Ajv,
root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string // reference to resolve
): SchemaEnv | undefined {
const p = this.opts.uriResolver.parse(ref)
const refPath = _getFullPath(this.opts.uriResolver, p)
let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)
// TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
if (Object.keys(root.schema).length > 0 && refPath === baseId) {
return getJsonPointer.call(this, p, root)
}
const id = normalizeId(refPath)
const schOrRef = this.refs[id] || this.schemas[id]
if (typeof schOrRef == "string") {
const sch = resolveSchema.call(this, root, schOrRef)
if (typeof sch?.schema !== "object") return
return getJsonPointer.call(this, p, sch)
}
if (typeof schOrRef?.schema !== "object") return
if (!schOrRef.validate) compileSchema.call(this, schOrRef)
if (id === normalizeId(ref)) {
const {schema} = schOrRef
const {schemaId} = this.opts
const schId = schema[schemaId]
if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
return new SchemaEnv({schema, schemaId, root, baseId})
}
return getJsonPointer.call(this, p, schOrRef)
} | 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,405 | function getJsonPointer(
this: Ajv,
parsedRef: URI.URIComponents,
{baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
if (parsedRef.fragment?.[0] !== "/") return
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean") return
const partSchema = schema[unescapeFragment(part)]
if (partSchema === undefined) return
schema = partSchema
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId]
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
}
}
let env: SchemaEnv | undefined
if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
env = resolveSchema.call(this, root, $ref)
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const {schemaId} = this.opts
env = env || new SchemaEnv({schema, schemaId, root, baseId})
if (env.schema !== env.root.schema) return env
return undefined
} | 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,406 | function getJsonPointer(
this: Ajv,
parsedRef: URI.URIComponents,
{baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
if (parsedRef.fragment?.[0] !== "/") return
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean") return
const partSchema = schema[unescapeFragment(part)]
if (partSchema === undefined) return
schema = partSchema
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId]
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
}
}
let env: SchemaEnv | undefined
if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
env = resolveSchema.call(this, root, $ref)
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const {schemaId} = this.opts
env = env || new SchemaEnv({schema, schemaId, root, baseId})
if (env.schema !== env.root.schema) return env
return undefined
} | 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,407 | function getJsonPointer(
this: Ajv,
parsedRef: URI.URIComponents,
{baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
if (parsedRef.fragment?.[0] !== "/") return
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean") return
const partSchema = schema[unescapeFragment(part)]
if (partSchema === undefined) return
schema = partSchema
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId]
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
}
}
let env: SchemaEnv | undefined
if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
env = resolveSchema.call(this, root, $ref)
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const {schemaId} = this.opts
env = env || new SchemaEnv({schema, schemaId, root, baseId})
if (env.schema !== env.root.schema) return env
return undefined
} | 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,408 | function getJsonPointer(
this: Ajv,
parsedRef: URI.URIComponents,
{baseId, schema, root}: SchemaEnv
): SchemaEnv | undefined {
if (parsedRef.fragment?.[0] !== "/") return
for (const part of parsedRef.fragment.slice(1).split("/")) {
if (typeof schema === "boolean") return
const partSchema = schema[unescapeFragment(part)]
if (partSchema === undefined) return
schema = partSchema
// TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
const schId = typeof schema === "object" && schema[this.opts.schemaId]
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
baseId = resolveUrl(this.opts.uriResolver, baseId, schId)
}
}
let env: SchemaEnv | undefined
if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)
env = resolveSchema.call(this, root, $ref)
}
// even though resolution failed we need to return SchemaEnv to throw exception
// so that compileAsync loads missing schema.
const {schemaId} = this.opts
env = env || new SchemaEnv({schema, schemaId, root, baseId})
if (env.schema !== env.root.schema) return env
return undefined
} | 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,409 | constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`)
this.missingRef = resolveUrl(resolver, baseId, ref)
this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))
} | interface UriResolver {
parse(uri: string): URI.URIComponents
resolve(base: string, path: string): string
serialize(component: URI.URIComponents): string
} |
2,410 | function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {
if (typeof schema == "boolean") return schema
if (Object.keys(schema).length === 0) return true
checkUnknownRules(it, schema)
return !schemaHasRules(schema, it.self.RULES.all)
} | type AnySchema = Schema | AsyncSchema |
2,411 | function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {
if (typeof schema == "boolean") return schema
if (Object.keys(schema).length === 0) return true
checkUnknownRules(it, schema)
return !schemaHasRules(schema, it.self.RULES.all)
} | 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,412 | function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
const {opts, self} = it
if (!opts.strictSchema) return
if (typeof schema === "boolean") return
const rules = self.RULES.keywords
for (const key in schema) {
if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
}
} | type AnySchema = Schema | AsyncSchema |
2,413 | function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {
const {opts, self} = it
if (!opts.strictSchema) return
if (typeof schema === "boolean") return
const rules = self.RULES.keywords
for (const key in schema) {
if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`)
}
} | 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,414 | function schemaHasRules(
schema: AnySchema,
rules: {[Key in string]?: boolean | Rule}
): boolean {
if (typeof schema == "boolean") return !schema
for (const key in schema) if (rules[key]) return true
return false
} | type AnySchema = Schema | AsyncSchema |
2,415 | function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {
if (typeof schema == "boolean") return !schema
for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true
return false
} | interface ValidationRules {
rules: RuleGroup[]
post: RuleGroup
all: {[Key in string]?: boolean | Rule} // rules that have to be validated
keywords: {[Key in string]?: boolean} // all known keywords (superset of "all")
types: ValidationTypes
} |
2,416 | function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {
if (typeof schema == "boolean") return !schema
for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true
return false
} | type AnySchema = Schema | AsyncSchema |
2,417 | function schemaRefOrVal(
{topSchemaRef, schemaPath}: SchemaObjCxt,
schema: unknown,
keyword: string,
$data?: string | false
): Code | number | boolean {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean") return schema
if (typeof schema == "string") return _`${schema}`
}
return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,418 | (
gen: CodeGen,
from: Name | T,
to: Name | Exclude<T, true> | undefined,
toName?: typeof Name
) => Name | T | 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,419 | (gen: CodeGen, from: Name, to: Name) => void | 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,420 | (gen: CodeGen, from: Name, to: Name) => void | 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,421 | (gen: CodeGen, from: T, to: Name) => void | 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,422 | (gen: CodeGen, from: T, to: Name) => void | 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,423 | (gen: CodeGen, res?: T) => Name | 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,424 | function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {
if (ps === true) return gen.var("props", true)
const props = gen.var("props", _`{}`)
if (ps !== undefined) setEvaluated(gen, props, ps)
return props
} | type EvaluatedProperties = {[K in string]?: true} | true |
2,425 | function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {
if (ps === true) return gen.var("props", true)
const props = gen.var("props", _`{}`)
if (ps !== undefined) setEvaluated(gen, props, ps)
return props
} | 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,426 | function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, 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,427 | function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
} | 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,428 | function useFunc(gen: CodeGen, f: {code: string}): Name {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),
})
} | 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,429 | function checkStrictMode(
it: SchemaCxt,
msg: string,
mode: boolean | "log" = it.opts.strictSchema
): void {
if (!mode) return
msg = `strict mode: ${msg}`
if (mode === true) throw new Error(msg)
it.self.logger.warn(msg)
} | 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,430 | function reportError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths,
overrideAllErrors?: boolean
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
if (overrideAllErrors ?? (compositeRule || allErrors)) {
addError(gen, errObj)
} else {
returnErrors(it, _`[${errObj}]`)
}
} | interface KeywordErrorDefinition {
message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
params?: Code | ((cxt: KeywordErrorCxt) => Code)
} |
2,431 | function reportError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths,
overrideAllErrors?: boolean
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
if (overrideAllErrors ?? (compositeRule || allErrors)) {
addError(gen, errObj)
} else {
returnErrors(it, _`[${errObj}]`)
}
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,432 | function reportError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths,
overrideAllErrors?: boolean
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
if (overrideAllErrors ?? (compositeRule || allErrors)) {
addError(gen, errObj)
} else {
returnErrors(it, _`[${errObj}]`)
}
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,433 | function reportExtraError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
addError(gen, errObj)
if (!(compositeRule || allErrors)) {
returnErrors(it, N.vErrors)
}
} | interface KeywordErrorDefinition {
message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
params?: Code | ((cxt: KeywordErrorCxt) => Code)
} |
2,434 | function reportExtraError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
addError(gen, errObj)
if (!(compositeRule || allErrors)) {
returnErrors(it, N.vErrors)
}
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,435 | function reportExtraError(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition = keywordError,
errorPaths?: ErrorPaths
): void {
const {it} = cxt
const {gen, compositeRule, allErrors} = it
const errObj = errorObjectCode(cxt, error, errorPaths)
addError(gen, errObj)
if (!(compositeRule || allErrors)) {
returnErrors(it, N.vErrors)
}
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,436 | function resetErrorsCount(gen: CodeGen, errsCount: Name): void {
gen.assign(N.errors, errsCount)
gen.if(_`${N.vErrors} !== null`, () =>
gen.if(
errsCount,
() => gen.assign(_`${N.vErrors}.length`, errsCount),
() => gen.assign(N.vErrors, null)
)
)
} | 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,437 | function resetErrorsCount(gen: CodeGen, errsCount: Name): void {
gen.assign(N.errors, errsCount)
gen.if(_`${N.vErrors} !== null`, () =>
gen.if(
errsCount,
() => gen.assign(_`${N.vErrors}.length`, errsCount),
() => gen.assign(N.vErrors, null)
)
)
} | 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,438 | function extendErrors({
gen,
keyword,
schemaValue,
data,
errsCount,
it,
}: KeywordErrorCxt): void {
/* istanbul ignore if */
if (errsCount === undefined) throw new Error("ajv implementation error")
const err = gen.name("err")
gen.forRange("i", errsCount, N.errors, (i) => {
gen.const(err, _`${N.vErrors}[${i}]`)
gen.if(_`${err}.instancePath === undefined`, () =>
gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))
)
gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)
if (it.opts.verbose) {
gen.assign(_`${err}.schema`, schemaValue)
gen.assign(_`${err}.data`, data)
}
})
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,439 | function addError(gen: CodeGen, errObj: Code): void {
const err = gen.const("err", errObj)
gen.if(
_`${N.vErrors} === null`,
() => gen.assign(N.vErrors, _`[${err}]`),
_`${N.vErrors}.push(${err})`
)
gen.code(_`${N.errors}++`)
} | type Code = _Code | Name |
2,440 | function addError(gen: CodeGen, errObj: Code): void {
const err = gen.const("err", errObj)
gen.if(
_`${N.vErrors} === null`,
() => gen.assign(N.vErrors, _`[${err}]`),
_`${N.vErrors}.push(${err})`
)
gen.code(_`${N.errors}++`)
} | 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,441 | function returnErrors(it: SchemaCxt, errs: Code): void {
const {gen, validateName, schemaEnv} = it
if (schemaEnv.$async) {
gen.throw(_`new ${it.ValidationError as Name}(${errs})`)
} else {
gen.assign(_`${validateName}.errors`, errs)
gen.return(false)
}
} | 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,442 | function returnErrors(it: SchemaCxt, errs: Code): void {
const {gen, validateName, schemaEnv} = it
if (schemaEnv.$async) {
gen.throw(_`new ${it.ValidationError as Name}(${errs})`)
} else {
gen.assign(_`${validateName}.errors`, errs)
gen.return(false)
}
} | type Code = _Code | Name |
2,443 | function errorObjectCode(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths?: ErrorPaths
): Code {
const {createErrors} = cxt.it
if (createErrors === false) return _`{}`
return errorObject(cxt, error, errorPaths)
} | interface KeywordErrorDefinition {
message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
params?: Code | ((cxt: KeywordErrorCxt) => Code)
} |
2,444 | function errorObjectCode(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths?: ErrorPaths
): Code {
const {createErrors} = cxt.it
if (createErrors === false) return _`{}`
return errorObject(cxt, error, errorPaths)
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,445 | function errorObjectCode(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths?: ErrorPaths
): Code {
const {createErrors} = cxt.it
if (createErrors === false) return _`{}`
return errorObject(cxt, error, errorPaths)
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,446 | function errorObject(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths: ErrorPaths = {}
): Code {
const {gen, it} = cxt
const keyValues: [Name, SafeExpr | string][] = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
]
extraErrorProps(cxt, error, keyValues)
return gen.object(...keyValues)
} | interface KeywordErrorDefinition {
message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
params?: Code | ((cxt: KeywordErrorCxt) => Code)
} |
2,447 | function errorObject(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths: ErrorPaths = {}
): Code {
const {gen, it} = cxt
const keyValues: [Name, SafeExpr | string][] = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
]
extraErrorProps(cxt, error, keyValues)
return gen.object(...keyValues)
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,448 | function errorObject(
cxt: KeywordErrorCxt,
error: KeywordErrorDefinition,
errorPaths: ErrorPaths = {}
): Code {
const {gen, it} = cxt
const keyValues: [Name, SafeExpr | string][] = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths),
]
extraErrorProps(cxt, error, keyValues)
return gen.object(...keyValues)
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,449 | function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {
const instPath = instancePath
? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`
: errorPath
return [N.instancePath, strConcat(N.instancePath, instPath)]
} | 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,450 | function errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {
const instPath = instancePath
? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`
: errorPath
return [N.instancePath, strConcat(N.instancePath, instPath)]
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,451 | function errorSchemaPath(
{keyword, it: {errSchemaPath}}: KeywordErrorCxt,
{schemaPath, parentSchema}: ErrorPaths
): [Name, string | Code] {
let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`
if (schemaPath) {
schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`
}
return [E.schemaPath, schPath]
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,452 | function errorSchemaPath(
{keyword, it: {errSchemaPath}}: KeywordErrorCxt,
{schemaPath, parentSchema}: ErrorPaths
): [Name, string | Code] {
let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`
if (schemaPath) {
schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`
}
return [E.schemaPath, schPath]
} | interface ErrorPaths {
instancePath?: Code
schemaPath?: string
parentSchema?: boolean
} |
2,453 | function extraErrorProps(
cxt: KeywordErrorCxt,
{params, message}: KeywordErrorDefinition,
keyValues: [Name, SafeExpr | string][]
): void {
const {keyword, data, schemaValue, it} = cxt
const {opts, propertyName, topSchemaRef, schemaPath} = it
keyValues.push(
[E.keyword, keyword],
[E.params, typeof params == "function" ? params(cxt) : params || _`{}`]
)
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message])
}
if (opts.verbose) {
keyValues.push(
[E.schema, schemaValue],
[E.parentSchema, _`${topSchemaRef}${schemaPath}`],
[N.data, data]
)
}
if (propertyName) keyValues.push([E.propertyName, propertyName])
} | interface KeywordErrorDefinition {
message: string | Code | ((cxt: KeywordErrorCxt) => string | Code)
params?: Code | ((cxt: KeywordErrorCxt) => Code)
} |
2,454 | function extraErrorProps(
cxt: KeywordErrorCxt,
{params, message}: KeywordErrorDefinition,
keyValues: [Name, SafeExpr | string][]
): void {
const {keyword, data, schemaValue, it} = cxt
const {opts, propertyName, topSchemaRef, schemaPath} = it
keyValues.push(
[E.keyword, keyword],
[E.params, typeof params == "function" ? params(cxt) : params || _`{}`]
)
if (opts.messages) {
keyValues.push([E.message, typeof message == "function" ? message(cxt) : message])
}
if (opts.verbose) {
keyValues.push(
[E.schema, schemaValue],
[E.parentSchema, _`${topSchemaRef}${schemaPath}`],
[N.data, data]
)
}
if (propertyName) keyValues.push([E.propertyName, propertyName])
} | interface KeywordErrorCxt {
gen: CodeGen
keyword: string
data: Name
$data?: string | false
schema: any // TODO
parentSchema?: AnySchemaObject
schemaCode: Code | number | boolean
schemaValue: Code | number | boolean
schemaType?: JSONType[]
errsCount?: Name
params: KeywordCxtParams
it: SchemaCxt
} |
2,455 | function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {
if (typeof schema == "boolean") return true
if (limit === true) return !hasRef(schema)
if (!limit) return false
return countKeys(schema) <= limit
} | type AnySchema = Schema | AsyncSchema |
2,456 | function hasRef(schema: AnySchemaObject): boolean {
for (const key in schema) {
if (REF_KEYWORDS.has(key)) return true
const sch = schema[key]
if (Array.isArray(sch) && sch.some(hasRef)) return true
if (typeof sch == "object" && hasRef(sch)) return true
}
return false
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,457 | function countKeys(schema: AnySchemaObject): number {
let count = 0
for (const key in schema) {
if (key === "$ref") return Infinity
count++
if (SIMPLE_INLINED.has(key)) continue
if (typeof schema[key] == "object") {
eachItem(schema[key], (sch) => (count += countKeys(sch)))
}
if (count === Infinity) return Infinity
}
return count
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,458 | function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string {
if (normalize !== false) id = normalizeId(id)
const p = resolver.parse(id)
return _getFullPath(resolver, p)
} | interface UriResolver {
parse(uri: string): URI.URIComponents
resolve(base: string, path: string): string
serialize(component: URI.URIComponents): string
} |
2,459 | function _getFullPath(resolver: UriResolver, p: URIComponents): string {
const serialized = resolver.serialize(p)
return serialized.split("#")[0] + "#"
} | interface UriResolver {
parse(uri: string): URI.URIComponents
resolve(base: string, path: string): string
serialize(component: URI.URIComponents): string
} |
2,460 | function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {
id = normalizeId(id)
return resolver.resolve(baseId, id)
} | interface UriResolver {
parse(uri: string): URI.URIComponents
resolve(base: string, path: string): string
serialize(component: URI.URIComponents): string
} |
2,461 | function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
if (typeof schema == "boolean") return {}
const {schemaId, uriResolver} = this.opts
const schId = normalizeId(schema[schemaId] || baseId)
const baseIds: {[JsonPtr in string]?: string} = {"": schId}
const pathPrefix = getFullPath(uriResolver, schId, false)
const localRefs: LocalRefs = {}
const schemaRefs: Set<string> = new Set()
traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined) return
const fullPath = pathPrefix + jsonPtr
let baseId = baseIds[parentJsonPtr]
if (typeof sch[schemaId] == "string") baseId = addRef.call(this, sch[schemaId])
addAnchor.call(this, sch.$anchor)
addAnchor.call(this, sch.$dynamicAnchor)
baseIds[jsonPtr] = baseId
function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
}
function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
}
})
return localRefs
function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
}
function ambiguos(ref: string): Error {
return new Error(`reference "${ref}" resolves to more than one schema`)
}
} | 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,462 | function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
if (typeof schema == "boolean") return {}
const {schemaId, uriResolver} = this.opts
const schId = normalizeId(schema[schemaId] || baseId)
const baseIds: {[JsonPtr in string]?: string} = {"": schId}
const pathPrefix = getFullPath(uriResolver, schId, false)
const localRefs: LocalRefs = {}
const schemaRefs: Set<string> = new Set()
traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined) return
const fullPath = pathPrefix + jsonPtr
let baseId = baseIds[parentJsonPtr]
if (typeof sch[schemaId] == "string") baseId = addRef.call(this, sch[schemaId])
addAnchor.call(this, sch.$anchor)
addAnchor.call(this, sch.$dynamicAnchor)
baseIds[jsonPtr] = baseId
function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
}
function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
}
})
return localRefs
function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
}
function ambiguos(ref: string): Error {
return new Error(`reference "${ref}" resolves to more than one schema`)
}
} | 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,463 | function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
if (typeof schema == "boolean") return {}
const {schemaId, uriResolver} = this.opts
const schId = normalizeId(schema[schemaId] || baseId)
const baseIds: {[JsonPtr in string]?: string} = {"": schId}
const pathPrefix = getFullPath(uriResolver, schId, false)
const localRefs: LocalRefs = {}
const schemaRefs: Set<string> = new Set()
traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined) return
const fullPath = pathPrefix + jsonPtr
let baseId = baseIds[parentJsonPtr]
if (typeof sch[schemaId] == "string") baseId = addRef.call(this, sch[schemaId])
addAnchor.call(this, sch.$anchor)
addAnchor.call(this, sch.$dynamicAnchor)
baseIds[jsonPtr] = baseId
function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
}
function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
}
})
return localRefs
function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
}
function ambiguos(ref: string): Error {
return new Error(`reference "${ref}" resolves to more than one schema`)
}
} | 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,464 | function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {
if (typeof schema == "boolean") return {}
const {schemaId, uriResolver} = this.opts
const schId = normalizeId(schema[schemaId] || baseId)
const baseIds: {[JsonPtr in string]?: string} = {"": schId}
const pathPrefix = getFullPath(uriResolver, schId, false)
const localRefs: LocalRefs = {}
const schemaRefs: Set<string> = new Set()
traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {
if (parentJsonPtr === undefined) return
const fullPath = pathPrefix + jsonPtr
let baseId = baseIds[parentJsonPtr]
if (typeof sch[schemaId] == "string") baseId = addRef.call(this, sch[schemaId])
addAnchor.call(this, sch.$anchor)
addAnchor.call(this, sch.$dynamicAnchor)
baseIds[jsonPtr] = baseId
function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
}
function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
}
})
return localRefs
function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
}
function ambiguos(ref: string): Error {
return new Error(`reference "${ref}" resolves to more than one schema`)
}
} | type AnySchema = Schema | AsyncSchema |
2,465 | function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
} | 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,466 | function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
} | 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,467 | function addRef(this: Ajv, ref: string): string {
// eslint-disable-next-line @typescript-eslint/unbound-method
const _resolve = this.opts.uriResolver.resolve
ref = normalizeId(baseId ? _resolve(baseId, ref) : ref)
if (schemaRefs.has(ref)) throw ambiguos(ref)
schemaRefs.add(ref)
let schOrRef = this.refs[ref]
if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]
if (typeof schOrRef == "object") {
checkAmbiguosRef(sch, schOrRef.schema, ref)
} else if (ref !== normalizeId(fullPath)) {
if (ref[0] === "#") {
checkAmbiguosRef(sch, localRefs[ref], ref)
localRefs[ref] = sch
} else {
this.refs[ref] = fullPath
}
}
return ref
} | 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,468 | function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
} | 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,469 | function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
} | 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,470 | function addAnchor(this: Ajv, anchor: unknown): void {
if (typeof anchor == "string") {
if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`)
addRef.call(this, `#${anchor}`)
}
} | 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,471 | function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {
if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)
} | type AnySchema = Schema | AsyncSchema |
2,472 | function topBoolOrEmptySchema(it: SchemaCxt): void {
const {gen, schema, validateName} = it
if (schema === false) {
falseSchemaError(it, false)
} else if (typeof schema == "object" && schema.$async === true) {
gen.return(N.data)
} else {
gen.assign(_`${validateName}.errors`, null)
gen.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,473 | function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {
const {gen, schema} = it
if (schema === false) {
gen.var(valid, false) // TODO var
falseSchemaError(it)
} else {
gen.var(valid, true) // TODO var
}
} | 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,474 | function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {
const {gen, schema} = it
if (schema === false) {
gen.var(valid, false) // TODO var
falseSchemaError(it)
} else {
gen.var(valid, true) // TODO var
}
} | 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,475 | function falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {
const {gen, data} = it
// TODO maybe some other interface should be used for non-keyword validation errors...
const cxt: KeywordErrorCxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it,
}
reportError(cxt, boolError, undefined, overrideAllErrors)
} | 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,476 | function validateFunctionCode(it: SchemaCxt): void {
if (isSchemaObj(it)) {
checkKeywords(it)
if (schemaCxtHasRules(it)) {
topSchemaObjCode(it)
return
}
}
validateFunction(it, () => topBoolOrEmptySchema(it))
} | 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,477 | function validateFunction(
{gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
body: Block
): void {
if (opts.code.es5) {
gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
destructureValCxtES5(gen, opts)
gen.code(body)
})
} else {
gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
gen.code(funcSourceUrl(schema, opts)).code(body)
)
}
} | type Block = Code | (() => void) |
2,478 | function validateFunction(
{gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
body: Block
): void {
if (opts.code.es5) {
gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
destructureValCxtES5(gen, opts)
gen.code(body)
})
} else {
gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
gen.code(funcSourceUrl(schema, opts)).code(body)
)
}
} | 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,479 | function destructureValCxt(opts: InstanceOptions): Code {
return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
N.data
}${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
} | type InstanceOptions = Options & RequiredInstanceOptions |
2,480 | function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
gen.if(
N.valCxt,
() => {
gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
},
() => {
gen.var(N.instancePath, _`""`)
gen.var(N.parentData, _`undefined`)
gen.var(N.parentDataProperty, _`undefined`)
gen.var(N.rootData, N.data)
if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
}
)
} | 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,481 | function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
gen.if(
N.valCxt,
() => {
gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
},
() => {
gen.var(N.instancePath, _`""`)
gen.var(N.parentData, _`undefined`)
gen.var(N.parentDataProperty, _`undefined`)
gen.var(N.rootData, N.data)
if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
}
)
} | type InstanceOptions = Options & RequiredInstanceOptions |
2,482 | function topSchemaObjCode(it: SchemaObjCxt): void {
const {schema, opts, gen} = it
validateFunction(it, () => {
if (opts.$comment && schema.$comment) commentKeyword(it)
checkNoDefault(it)
gen.let(N.vErrors, null)
gen.let(N.errors, 0)
if (opts.unevaluated) resetEvaluated(it)
typeAndKeywords(it)
returnResults(it)
})
return
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,483 | function resetEvaluated(it: SchemaObjCxt): void {
// TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
const {gen, validateName} = it
it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,484 | function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
const schId = typeof schema == "object" && schema[opts.schemaId]
return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
} | type AnySchema = Schema | AsyncSchema |
2,485 | function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
const schId = typeof schema == "object" && schema[opts.schemaId]
return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
} | type InstanceOptions = Options & RequiredInstanceOptions |
2,486 | function subschemaCode(it: SchemaCxt, valid: Name): void {
if (isSchemaObj(it)) {
checkKeywords(it)
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid)
return
}
}
boolOrEmptySchema(it, valid)
} | 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,487 | function subschemaCode(it: SchemaCxt, valid: Name): void {
if (isSchemaObj(it)) {
checkKeywords(it)
if (schemaCxtHasRules(it)) {
subSchemaObjCode(it, valid)
return
}
}
boolOrEmptySchema(it, valid)
} | 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,488 | function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
if (typeof schema == "boolean") return !schema
for (const key in schema) if (self.RULES.all[key]) return true
return false
} | 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,489 | function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
return typeof it.schema != "boolean"
} | 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,490 | function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
const {schema, gen, opts} = it
if (opts.$comment && schema.$comment) commentKeyword(it)
updateContext(it)
checkAsyncSchema(it)
const errsCount = gen.const("_errs", N.errors)
typeAndKeywords(it, errsCount)
// TODO var
gen.var(valid, _`${errsCount} === ${N.errors}`)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,491 | function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
const {schema, gen, opts} = it
if (opts.$comment && schema.$comment) commentKeyword(it)
updateContext(it)
checkAsyncSchema(it)
const errsCount = gen.const("_errs", N.errors)
typeAndKeywords(it, errsCount)
// TODO var
gen.var(valid, _`${errsCount} === ${N.errors}`)
} | 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,492 | function checkKeywords(it: SchemaObjCxt): void {
checkUnknownRules(it)
checkRefsAndKeywords(it)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,493 | function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
const types = getSchemaTypes(it.schema)
const checkedTypes = coerceAndCheckDataType(it, types)
schemaKeywords(it, types, !checkedTypes, errsCount)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,494 | function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
const types = getSchemaTypes(it.schema)
const checkedTypes = coerceAndCheckDataType(it, types)
schemaKeywords(it, types, !checkedTypes, errsCount)
} | 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,495 | function checkRefsAndKeywords(it: SchemaObjCxt): void {
const {schema, errSchemaPath, opts, self} = it
if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,496 | function checkNoDefault(it: SchemaObjCxt): void {
const {schema, opts} = it
if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
checkStrictMode(it, "default is ignored in the schema root")
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,497 | function updateContext(it: SchemaObjCxt): void {
const schId = it.schema[it.opts.schemaId]
if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,498 | function checkAsyncSchema(it: SchemaObjCxt): void {
if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
2,499 | function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
const msg = schema.$comment
if (opts.$comment === true) {
gen.code(_`${N.self}.logger.log(${msg})`)
} else if (typeof opts.$comment == "function") {
const schemaPath = str`${errSchemaPath}/$comment`
const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
}
} | interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.