Skip to content

Commit

Permalink
refactor: typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Aug 16, 2020
1 parent 2549456 commit 8e48c18
Show file tree
Hide file tree
Showing 14 changed files with 83 additions and 76 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ overrides:
"@typescript-eslint/restrict-plus-operands": off
"@typescript-eslint/no-unsafe-return": off
"@typescript-eslint/no-var-requires": off
"@typescript-eslint/no-empty-function": off
"@typescript-eslint/no-this-alias": off
"@typescript-eslint/no-implied-eval": off
rules:
block-scoped-var: error
callback-return: error
Expand Down
File renamed without changes.
10 changes: 5 additions & 5 deletions lib/ajv.js → lib/ajv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const META_SUPPORT_DATA = ["/properties"]
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
function Ajv(opts): void {
if (!(this instanceof Ajv)) return new Ajv(opts)
opts = this._opts = {...(opts || {})}
setLogger(this)
Expand Down Expand Up @@ -280,7 +280,7 @@ function removeSchema(schemaKeyRef) {
return this
}

function _removeAllSchemas(self, schemas, regex) {
function _removeAllSchemas(self, schemas, regex?: RegExp) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef]
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
Expand Down Expand Up @@ -365,10 +365,10 @@ function _compile(schemaObj, root) {
return v

/* @this {*} - custom context, see passContext option */
function callValidate() {
function callValidate(...args) {
/* jshint validthis: true */
var _validate = schemaObj.validate
var result = _validate.apply(this, arguments)
var result = _validate.apply(this, args)
callValidate.errors = _validate.errors
return result
}
Expand Down Expand Up @@ -438,7 +438,7 @@ function addInitialFormats(self) {
}
}

function addInitialKeywords(self, keywords, skipValidation) {
function addInitialKeywords(self, keywords, skipValidation?: boolean) {
for (var name in keywords) {
var keyword = keywords[name]
self.addKeyword(name, keyword, skipValidation)
Expand Down
16 changes: 6 additions & 10 deletions lib/compile/async.js → lib/compile/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import {MissingRefError} from "./error_classes"

module.exports = compileAsync

type Callback = (...args: any[]) => void

/**
* 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.
Expand All @@ -11,7 +13,7 @@ module.exports = compileAsync
* @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
* @return {Promise} promise that resolves with a validating function.
*/
function compileAsync(schema, meta, callback) {
function compileAsync(schema, meta?: boolean | Callback, callback?: Callback) {
/* eslint no-shadow: 0 */
/* jshint validthis: true */
var self = this
Expand All @@ -25,12 +27,12 @@ function compileAsync(schema, meta, callback) {
}

var p = loadMetaSchemaOf(schema).then(() => {
var schemaObj = self._addSchema(schema, undefined, meta)
var schemaObj = this._addSchema(schema, undefined, meta)
return schemaObj.validate || _compileAsync(schemaObj)
})

if (callback) {
p.then((v) => callback(null, v), callback)
p.then((v) => (<Callback>callback)(null, v), callback)
}

return p
Expand All @@ -53,13 +55,7 @@ function compileAsync(schema, meta, callback) {
function loadMissingSchema(e) {
var ref = e.missingSchema
if (added(ref)) {
throw new Error(
"Schema " +
ref +
" is loaded but " +
e.missingRef +
" cannot be resolved"
)
throw new Error("Schema " + ref + " is loaded but " + e.missingRef + " cannot be resolved")
}

var schemaPromise = self._loadingSchemas[ref]
Expand Down
65 changes: 41 additions & 24 deletions lib/compile/index.js → lib/compile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import CodeGen from "./codegen"
import {toQuotedString} from "./util"
import {MissingRefError} from "./error_classes"
import validateCode from "./validate"
import {Rule} from "./rules"
import {CompilationContext, KeywordDefinition, ErrorObject} from "../types"

const equal = require("fast-deep-equal")
const ucs2length = require("./ucs2length")
Expand Down Expand Up @@ -35,16 +37,31 @@ function compile(schema, root, localRefs, baseId) {
opts = this._opts,
refVal = [undefined],
refs = {},
patterns = [],
patterns: string[] = [],
patternsHash = {},
defaults = [],
defaults: any[] = [],
defaultsHash = {},
customRules = []
customRules: any[] = []

root = root || {schema: schema, refVal: refVal, refs: refs}

interface CallValidate {
(): any
errors?: null | ErrorObject[]
}

var c = checkCompiling.call(this, schema, root, baseId)
var compilation = this._compilations[c.index]
const compilation = this._compilations[c.index]

/* @this {*} - custom context, see passContext option */
const callValidate: CallValidate = function (...args) {
var validate = compilation.validate
/* eslint-disable no-invalid-this */
var result = validate.apply(this, args)
callValidate.errors = validate.errors
return result
}

if (c.compiling) return (compilation.callValidate = callValidate)

var formats = this._formats
Expand All @@ -68,15 +85,6 @@ function compile(schema, root, localRefs, baseId) {
endCompiling.call(this, schema, root, baseId)
}

/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var validate = compilation.validate
var result = validate.apply(this, arguments)
callValidate.errors = validate.errors
return result
}

function localCompile(_schema, _root, localRefs, baseId) {
var isRoot = !_root || (_root && _root.schema === _schema)
if (_root.schema !== root.schema) {
Expand All @@ -95,6 +103,7 @@ function compile(schema, root, localRefs, baseId) {
schemaPath: "",
errSchemaPath: "#",
errorPath: '""',
dataPathArr: [""],
level: 0,
dataLevel: 0,
data: "data", // TODO get unique name when passed from applicator keywords
Expand Down Expand Up @@ -175,7 +184,7 @@ function compile(schema, root, localRefs, baseId) {
return validate
}

function resolveRef(baseId, ref, isRoot) {
function resolveRef(baseId: string, ref: string, isRoot: boolean) {
ref = resolve.url(baseId, ref)
var refIndex = refs[ref]
var _refVal, refCode
Expand Down Expand Up @@ -212,7 +221,7 @@ function compile(schema, root, localRefs, baseId) {
}
}

function addLocalRef(ref, v) {
function addLocalRef(ref, v?: any): string {
var refId = refVal.length
refVal[refId] = v
refs[ref] = refId
Expand Down Expand Up @@ -243,7 +252,7 @@ function compile(schema, root, localRefs, baseId) {
return "pattern" + index
}

function useDefault(value) {
function useDefault(value: any): string {
switch (typeof value) {
case "boolean":
case "number":
Expand All @@ -259,20 +268,28 @@ function compile(schema, root, localRefs, baseId) {
defaults[index] = value
}
return "default" + index
default:
throw new Error(`unsupported default type "${typeof value}"`)
}
}

function useCustomRule(rule, schema, parentSchema, it) {
function useCustomRule(
rule: Rule,
schema: any,
parentSchema: object,
it: CompilationContext
): any {
const ruleDef = rule.definition as KeywordDefinition
if (self._opts.validateSchema !== false) {
var deps = rule.definition.dependencies
var deps = ruleDef.dependencies
if (
deps &&
!deps.every((keyword) => Object.prototype.hasOwnProperty.call(parentSchema, keyword))
) {
throw new Error("parent schema must have all required keywords: " + deps.join(","))
}

var validateSchema = rule.definition.validateSchema
var validateSchema = ruleDef.validateSchema
if (validateSchema) {
var valid = validateSchema(schema)
if (!valid) {
Expand All @@ -283,9 +300,9 @@ function compile(schema, root, localRefs, baseId) {
}
}

var compile = rule.definition.compile,
inline = rule.definition.inline,
macro = rule.definition.macro
var compile = ruleDef.compile,
inline = ruleDef.inline,
macro = ruleDef.macro

var validate
if (compile) {
Expand All @@ -296,7 +313,7 @@ function compile(schema, root, localRefs, baseId) {
} else if (inline) {
validate = inline.call(self, it, rule.keyword, schema, parentSchema)
} else {
validate = rule.definition.validate
validate = ruleDef.validate
if (!validate) return
}

Expand All @@ -309,7 +326,7 @@ function compile(schema, root, localRefs, baseId) {

return {
code: "customRule" + index,
validate: validate,
validate,
}
}
}
Expand Down
28 changes: 7 additions & 21 deletions lib/compile/resolve.js → lib/compile/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ function resolve(compile, root, ref) {
}

if (schema instanceof SchemaObject) {
v =
schema.validate ||
compile.call(this, schema.schema, root, undefined, baseId)
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId)
} else if (schema !== undefined) {
v = inlineRef(schema, this._opts.inlineRefs)
? schema
Expand Down Expand Up @@ -213,7 +211,7 @@ function countKeys(schema) {
return count
}

export function getFullPath(id, normalize) {
export function getFullPath(id: string, normalize?: boolean): string {
if (normalize !== false) id = normalizeId(id)
var p = URI.parse(id)
return _getFullPath(p)
Expand All @@ -224,11 +222,11 @@ function _getFullPath(p) {
}

var TRAILING_SLASH_HASH = /#\/?$/
export function normalizeId(id) {
export function normalizeId(id: string): string {
return id ? id.replace(TRAILING_SLASH_HASH, "") : ""
}

export function resolveUrl(baseId, id) {
export function resolveUrl(baseId: string, id: string): string {
id = normalizeId(id)
return URI.resolve(baseId, id)
}
Expand All @@ -244,23 +242,13 @@ function resolveIds(schema) {
traverse(
schema,
{allKeys: true},
(
sch,
jsonPtr,
rootSchema,
parentJsonPtr,
parentKeyword,
parentSchema,
keyIndex
) => {
(sch, jsonPtr, _1, parentJsonPtr, parentKeyword, _2, keyIndex) => {
if (jsonPtr === "") return
var id = sch.$id
var baseId = baseIds[parentJsonPtr]
var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword
if (keyIndex !== undefined) {
fullPath +=
"/" +
(typeof keyIndex == "number" ? keyIndex : escapeFragment(keyIndex))
fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : escapeFragment(keyIndex))
}

if (typeof id == "string") {
Expand All @@ -275,9 +263,7 @@ function resolveIds(schema) {
} else if (id !== normalizeId(fullPath)) {
if (id[0] === "#") {
if (localRefs[id] && !equal(sch, localRefs[id])) {
throw new Error(
'id "' + id + '" resolves to more than one schema'
)
throw new Error('id "' + id + '" resolves to more than one schema')
}
localRefs[id] = sch
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/compile/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export interface Rule {
custom?: true
}

export default function rules() {
export default function rules(): ValidationRules {
const ALL = ["type", "$comment"]
const KEYWORDS = [
"$schema",
Expand Down
3 changes: 3 additions & 0 deletions lib/compile/schema_obj.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export default class SchemaObject {
schema?: any
validate?: () => any

constructor(obj: object) {
Object.assign(this, obj)
}
Expand Down
2 changes: 0 additions & 2 deletions lib/compile/validate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@ function updateTopContext(it: CompilationContext): void {
it.rootId = resolve.fullPath(it.root.schema.$id)
it.baseId = it.baseId || it.rootId
delete it.isTop

it.dataPathArr = [""]
}

function checkNoDefault({
Expand Down
7 changes: 3 additions & 4 deletions lib/definition_schema.js → lib/definition_schema.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
var metaSchema = require("./refs/json-schema-draft-07.json")
const metaSchema = require("./refs/json-schema-draft-07.json")

module.exports = {
$id:
"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",
export const definitionSchema: object = {
$id: "https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",
definitions: {
simpleTypes: metaSchema.definitions.simpleTypes,
},
Expand Down
2 changes: 1 addition & 1 deletion lib/keyword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {ValidationRules, Rule} from "./compile/rules"
import {reportError} from "./compile/errors"
import {getData} from "./compile/util"
import {schemaRefOrVal} from "./vocabularies/util"
import {definitionSchema} from "./definition_schema"

const IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i
const customRuleCode = require("./dotjs/custom")
const definitionSchema = require("./definition_schema")

/**
* Define vocabulary
Expand Down
Loading

0 comments on commit 8e48c18

Please sign in to comment.