update electron to v43
This commit is contained in:
parent
68ac0beedf
commit
fb6c8b6ee9
5385 changed files with 513060 additions and 123058 deletions
81
electron/node_modules/ajv/lib/2019.ts
generated
vendored
Normal file
81
electron/node_modules/ajv/lib/2019.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import type {AnySchemaObject} from "./types"
|
||||
import AjvCore, {Options} from "./core"
|
||||
|
||||
import draft7Vocabularies from "./vocabularies/draft7"
|
||||
import dynamicVocabulary from "./vocabularies/dynamic"
|
||||
import nextVocabulary from "./vocabularies/next"
|
||||
import unevaluatedVocabulary from "./vocabularies/unevaluated"
|
||||
import discriminator from "./vocabularies/discriminator"
|
||||
import addMetaSchema2019 from "./refs/json-schema-2019-09"
|
||||
|
||||
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"
|
||||
|
||||
export class Ajv2019 extends AjvCore {
|
||||
constructor(opts: Options = {}) {
|
||||
super({
|
||||
...opts,
|
||||
dynamicRef: true,
|
||||
next: true,
|
||||
unevaluated: true,
|
||||
})
|
||||
}
|
||||
|
||||
_addVocabularies(): void {
|
||||
super._addVocabularies()
|
||||
this.addVocabulary(dynamicVocabulary)
|
||||
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
|
||||
this.addVocabulary(nextVocabulary)
|
||||
this.addVocabulary(unevaluatedVocabulary)
|
||||
if (this.opts.discriminator) this.addKeyword(discriminator)
|
||||
}
|
||||
|
||||
_addDefaultMetaSchema(): void {
|
||||
super._addDefaultMetaSchema()
|
||||
const {$data, meta} = this.opts
|
||||
if (!meta) return
|
||||
addMetaSchema2019.call(this, $data)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = exports = Ajv2019
|
||||
module.exports.Ajv2019 = Ajv2019
|
||||
Object.defineProperty(exports, "__esModule", {value: true})
|
||||
|
||||
export default Ajv2019
|
||||
|
||||
export {
|
||||
Format,
|
||||
FormatDefinition,
|
||||
AsyncFormatDefinition,
|
||||
KeywordDefinition,
|
||||
KeywordErrorDefinition,
|
||||
CodeKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
Vocabulary,
|
||||
Schema,
|
||||
SchemaObject,
|
||||
AnySchemaObject,
|
||||
AsyncSchema,
|
||||
AnySchema,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
ErrorObject,
|
||||
ErrorNoParams,
|
||||
} from "./types"
|
||||
|
||||
export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
|
||||
export {SchemaCxt, SchemaObjCxt} from "./compile"
|
||||
export {KeywordCxt} from "./compile/validate"
|
||||
export {DefinedError} from "./vocabularies/errors"
|
||||
export {JSONType} from "./compile/rules"
|
||||
export {JSONSchemaType} from "./types/json-schema"
|
||||
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
|
||||
export {default as ValidationError} from "./runtime/validation_error"
|
||||
export {default as MissingRefError} from "./compile/ref_error"
|
||||
75
electron/node_modules/ajv/lib/2020.ts
generated
vendored
Normal file
75
electron/node_modules/ajv/lib/2020.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import type {AnySchemaObject} from "./types"
|
||||
import AjvCore, {Options} from "./core"
|
||||
|
||||
import draft2020Vocabularies from "./vocabularies/draft2020"
|
||||
import discriminator from "./vocabularies/discriminator"
|
||||
import addMetaSchema2020 from "./refs/json-schema-2020-12"
|
||||
|
||||
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"
|
||||
|
||||
export class Ajv2020 extends AjvCore {
|
||||
constructor(opts: Options = {}) {
|
||||
super({
|
||||
...opts,
|
||||
dynamicRef: true,
|
||||
next: true,
|
||||
unevaluated: true,
|
||||
})
|
||||
}
|
||||
|
||||
_addVocabularies(): void {
|
||||
super._addVocabularies()
|
||||
draft2020Vocabularies.forEach((v) => this.addVocabulary(v))
|
||||
if (this.opts.discriminator) this.addKeyword(discriminator)
|
||||
}
|
||||
|
||||
_addDefaultMetaSchema(): void {
|
||||
super._addDefaultMetaSchema()
|
||||
const {$data, meta} = this.opts
|
||||
if (!meta) return
|
||||
addMetaSchema2020.call(this, $data)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = exports = Ajv2020
|
||||
module.exports.Ajv2020 = Ajv2020
|
||||
Object.defineProperty(exports, "__esModule", {value: true})
|
||||
|
||||
export default Ajv2020
|
||||
|
||||
export {
|
||||
Format,
|
||||
FormatDefinition,
|
||||
AsyncFormatDefinition,
|
||||
KeywordDefinition,
|
||||
KeywordErrorDefinition,
|
||||
CodeKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
Vocabulary,
|
||||
Schema,
|
||||
SchemaObject,
|
||||
AnySchemaObject,
|
||||
AsyncSchema,
|
||||
AnySchema,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
ErrorObject,
|
||||
ErrorNoParams,
|
||||
} from "./types"
|
||||
|
||||
export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
|
||||
export {SchemaCxt, SchemaObjCxt} from "./compile"
|
||||
export {KeywordCxt} from "./compile/validate"
|
||||
export {DefinedError} from "./vocabularies/errors"
|
||||
export {JSONType} from "./compile/rules"
|
||||
export {JSONSchemaType} from "./types/json-schema"
|
||||
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
|
||||
export {default as ValidationError} from "./runtime/validation_error"
|
||||
export {default as MissingRefError} from "./compile/ref_error"
|
||||
402
electron/node_modules/ajv/lib/ajv.d.ts
generated
vendored
402
electron/node_modules/ajv/lib/ajv.d.ts
generated
vendored
|
|
@ -1,402 +0,0 @@
|
|||
declare var ajv: {
|
||||
(options?: ajv.Options): ajv.Ajv;
|
||||
new(options?: ajv.Options): ajv.Ajv;
|
||||
ValidationError: typeof AjvErrors.ValidationError;
|
||||
MissingRefError: typeof AjvErrors.MissingRefError;
|
||||
$dataMetaSchema: object;
|
||||
}
|
||||
|
||||
declare namespace AjvErrors {
|
||||
class ValidationError extends Error {
|
||||
constructor(errors: Array<ajv.ErrorObject>);
|
||||
|
||||
message: string;
|
||||
errors: Array<ajv.ErrorObject>;
|
||||
ajv: true;
|
||||
validation: true;
|
||||
}
|
||||
|
||||
class MissingRefError extends Error {
|
||||
constructor(baseId: string, ref: string, message?: string);
|
||||
static message: (baseId: string, ref: string) => string;
|
||||
|
||||
message: string;
|
||||
missingRef: string;
|
||||
missingSchema: string;
|
||||
}
|
||||
}
|
||||
|
||||
declare namespace ajv {
|
||||
type ValidationError = AjvErrors.ValidationError;
|
||||
|
||||
type MissingRefError = AjvErrors.MissingRefError;
|
||||
|
||||
interface Ajv {
|
||||
/**
|
||||
* Validate data using schema
|
||||
* Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default).
|
||||
* @param {string|object|Boolean} schemaKeyRef key, ref or schema object
|
||||
* @param {Any} data to be validated
|
||||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
|
||||
*/
|
||||
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>;
|
||||
/**
|
||||
* Create validating function for passed schema.
|
||||
* @param {object|Boolean} schema schema object
|
||||
* @return {Function} validating function
|
||||
*/
|
||||
compile(schema: object | boolean): ValidateFunction;
|
||||
/**
|
||||
* Creates validating function for passed schema with asynchronous loading of missing schemas.
|
||||
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
|
||||
* @this Ajv
|
||||
* @param {object|Boolean} schema schema object
|
||||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
|
||||
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function.
|
||||
* @return {PromiseLike<ValidateFunction>} validating function
|
||||
*/
|
||||
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>;
|
||||
/**
|
||||
* Adds schema to the instance.
|
||||
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
|
||||
* @param {string} key 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`.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addSchema(schema: Array<object> | object, key?: string): Ajv;
|
||||
/**
|
||||
* Add schema that will be used to validate other schemas
|
||||
* options in META_IGNORE_OPTIONS are alway set to false
|
||||
* @param {object} schema schema object
|
||||
* @param {string} key optional schema key
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addMetaSchema(schema: object, key?: string): Ajv;
|
||||
/**
|
||||
* Validate schema
|
||||
* @param {object|Boolean} schema schema to validate
|
||||
* @return {Boolean} true if schema is valid
|
||||
*/
|
||||
validateSchema(schema: object | boolean): boolean;
|
||||
/**
|
||||
* Get compiled schema from the instance by `key` or `ref`.
|
||||
* @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
|
||||
* @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema.
|
||||
*/
|
||||
getSchema(keyRef: string): ValidateFunction | 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.
|
||||
* @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv;
|
||||
/**
|
||||
* Add custom format
|
||||
* @param {string} name format name
|
||||
* @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv;
|
||||
/**
|
||||
* Define custom keyword
|
||||
* @this Ajv
|
||||
* @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords.
|
||||
* @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addKeyword(keyword: string, definition: KeywordDefinition): Ajv;
|
||||
/**
|
||||
* Get keyword definition
|
||||
* @this Ajv
|
||||
* @param {string} keyword pre-defined or custom keyword.
|
||||
* @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
|
||||
*/
|
||||
getKeyword(keyword: string): object | boolean;
|
||||
/**
|
||||
* Remove keyword
|
||||
* @this Ajv
|
||||
* @param {string} keyword pre-defined or custom keyword.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
removeKeyword(keyword: string): Ajv;
|
||||
/**
|
||||
* Validate keyword
|
||||
* @this Ajv
|
||||
* @param {object} definition keyword definition object
|
||||
* @param {boolean} throwError true to throw exception if definition is invalid
|
||||
* @return {boolean} validation result
|
||||
*/
|
||||
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean;
|
||||
/**
|
||||
* Convert array of error message objects to string
|
||||
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used.
|
||||
* @param {object} options optional options with properties `separator` and `dataVar`.
|
||||
* @return {string} human readable string with all errors descriptions
|
||||
*/
|
||||
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
|
||||
errors?: Array<ErrorObject> | null;
|
||||
_opts: Options;
|
||||
}
|
||||
|
||||
interface CustomLogger {
|
||||
log(...args: any[]): any;
|
||||
warn(...args: any[]): any;
|
||||
error(...args: any[]): any;
|
||||
}
|
||||
|
||||
interface ValidateFunction {
|
||||
(
|
||||
data: any,
|
||||
dataPath?: string,
|
||||
parentData?: object | Array<any>,
|
||||
parentDataProperty?: string | number,
|
||||
rootData?: object | Array<any>
|
||||
): boolean | PromiseLike<any>;
|
||||
schema?: object | boolean;
|
||||
errors?: null | Array<ErrorObject>;
|
||||
refs?: object;
|
||||
refVal?: Array<any>;
|
||||
root?: ValidateFunction | object;
|
||||
$async?: true;
|
||||
source?: object;
|
||||
}
|
||||
|
||||
interface Options {
|
||||
$data?: boolean;
|
||||
allErrors?: boolean;
|
||||
verbose?: boolean;
|
||||
jsonPointers?: boolean;
|
||||
uniqueItems?: boolean;
|
||||
unicode?: boolean;
|
||||
format?: false | string;
|
||||
formats?: object;
|
||||
keywords?: object;
|
||||
unknownFormats?: true | string[] | 'ignore';
|
||||
schemas?: Array<object> | object;
|
||||
schemaId?: '$id' | 'id' | 'auto';
|
||||
missingRefs?: true | 'ignore' | 'fail';
|
||||
extendRefs?: true | 'ignore' | 'fail';
|
||||
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>;
|
||||
removeAdditional?: boolean | 'all' | 'failing';
|
||||
useDefaults?: boolean | 'empty' | 'shared';
|
||||
coerceTypes?: boolean | 'array';
|
||||
strictDefaults?: boolean | 'log';
|
||||
strictKeywords?: boolean | 'log';
|
||||
strictNumbers?: boolean;
|
||||
async?: boolean | string;
|
||||
transpile?: string | ((code: string) => string);
|
||||
meta?: boolean | object;
|
||||
validateSchema?: boolean | 'log';
|
||||
addUsedSchema?: boolean;
|
||||
inlineRefs?: boolean | number;
|
||||
passContext?: boolean;
|
||||
loopRequired?: number;
|
||||
ownProperties?: boolean;
|
||||
multipleOfPrecision?: boolean | number;
|
||||
errorDataPath?: string,
|
||||
messages?: boolean;
|
||||
sourceCode?: boolean;
|
||||
processCode?: (code: string, schema: object) => string;
|
||||
cache?: object;
|
||||
logger?: CustomLogger | false;
|
||||
nullable?: boolean;
|
||||
serialize?: ((schema: object | boolean) => any) | false;
|
||||
regExp?: (pattern: string) => RegExpLike;
|
||||
}
|
||||
|
||||
interface RegExpLike {
|
||||
test: (s: string) => boolean;
|
||||
}
|
||||
|
||||
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);
|
||||
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>);
|
||||
|
||||
interface NumberFormatDefinition {
|
||||
type: "number",
|
||||
validate: NumberFormatValidator;
|
||||
compare?: (data1: number, data2: number) => number;
|
||||
async?: boolean;
|
||||
}
|
||||
|
||||
interface StringFormatDefinition {
|
||||
type?: "string",
|
||||
validate: FormatValidator;
|
||||
compare?: (data1: string, data2: string) => number;
|
||||
async?: boolean;
|
||||
}
|
||||
|
||||
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
|
||||
|
||||
interface KeywordDefinition {
|
||||
type?: string | Array<string>;
|
||||
async?: boolean;
|
||||
$data?: boolean;
|
||||
errors?: boolean | string;
|
||||
metaSchema?: object;
|
||||
// schema: false makes validate not to expect schema (ValidateFunction)
|
||||
schema?: boolean;
|
||||
statements?: boolean;
|
||||
dependencies?: Array<string>;
|
||||
modifying?: boolean;
|
||||
valid?: boolean;
|
||||
// one and only one of the following properties should be present
|
||||
validate?: SchemaValidateFunction | ValidateFunction;
|
||||
compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction;
|
||||
macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean;
|
||||
inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string;
|
||||
}
|
||||
|
||||
interface CompilationContext {
|
||||
level: number;
|
||||
dataLevel: number;
|
||||
dataPathArr: string[];
|
||||
schema: any;
|
||||
schemaPath: string;
|
||||
baseId: string;
|
||||
async: boolean;
|
||||
opts: Options;
|
||||
formats: {
|
||||
[index: string]: FormatDefinition | undefined;
|
||||
};
|
||||
keywords: {
|
||||
[index: string]: KeywordDefinition | undefined;
|
||||
};
|
||||
compositeRule: boolean;
|
||||
validate: (schema: object) => boolean;
|
||||
util: {
|
||||
copy(obj: any, target?: any): any;
|
||||
toHash(source: string[]): { [index: string]: true | undefined };
|
||||
equal(obj: any, target: any): boolean;
|
||||
getProperty(str: string): string;
|
||||
schemaHasRules(schema: object, rules: any): string;
|
||||
escapeQuotes(str: string): string;
|
||||
toQuotedString(str: string): string;
|
||||
getData(jsonPointer: string, dataLevel: number, paths: string[]): string;
|
||||
escapeJsonPointer(str: string): string;
|
||||
unescapeJsonPointer(str: string): string;
|
||||
escapeFragment(str: string): string;
|
||||
unescapeFragment(str: string): string;
|
||||
};
|
||||
self: Ajv;
|
||||
}
|
||||
|
||||
interface SchemaValidateFunction {
|
||||
(
|
||||
schema: any,
|
||||
data: any,
|
||||
parentSchema?: object,
|
||||
dataPath?: string,
|
||||
parentData?: object | Array<any>,
|
||||
parentDataProperty?: string | number,
|
||||
rootData?: object | Array<any>
|
||||
): boolean | PromiseLike<any>;
|
||||
errors?: Array<ErrorObject>;
|
||||
}
|
||||
|
||||
interface ErrorsTextOptions {
|
||||
separator?: string;
|
||||
dataVar?: string;
|
||||
}
|
||||
|
||||
interface ErrorObject {
|
||||
keyword: string;
|
||||
dataPath: string;
|
||||
schemaPath: string;
|
||||
params: ErrorParameters;
|
||||
// Added to validation errors of propertyNames keyword schema
|
||||
propertyName?: string;
|
||||
// Excluded if messages set to false.
|
||||
message?: string;
|
||||
// These are added with the `verbose` option.
|
||||
schema?: any;
|
||||
parentSchema?: object;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
|
||||
DependenciesParams | FormatParams | ComparisonParams |
|
||||
MultipleOfParams | PatternParams | RequiredParams |
|
||||
TypeParams | UniqueItemsParams | CustomParams |
|
||||
PatternRequiredParams | PropertyNamesParams |
|
||||
IfParams | SwitchParams | NoParams | EnumParams;
|
||||
|
||||
interface RefParams {
|
||||
ref: string;
|
||||
}
|
||||
|
||||
interface LimitParams {
|
||||
limit: number;
|
||||
}
|
||||
|
||||
interface AdditionalPropertiesParams {
|
||||
additionalProperty: string;
|
||||
}
|
||||
|
||||
interface DependenciesParams {
|
||||
property: string;
|
||||
missingProperty: string;
|
||||
depsCount: number;
|
||||
deps: string;
|
||||
}
|
||||
|
||||
interface FormatParams {
|
||||
format: string
|
||||
}
|
||||
|
||||
interface ComparisonParams {
|
||||
comparison: string;
|
||||
limit: number | string;
|
||||
exclusive: boolean;
|
||||
}
|
||||
|
||||
interface MultipleOfParams {
|
||||
multipleOf: number;
|
||||
}
|
||||
|
||||
interface PatternParams {
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
interface RequiredParams {
|
||||
missingProperty: string;
|
||||
}
|
||||
|
||||
interface TypeParams {
|
||||
type: string;
|
||||
}
|
||||
|
||||
interface UniqueItemsParams {
|
||||
i: number;
|
||||
j: number;
|
||||
}
|
||||
|
||||
interface CustomParams {
|
||||
keyword: string;
|
||||
}
|
||||
|
||||
interface PatternRequiredParams {
|
||||
missingPattern: string;
|
||||
}
|
||||
|
||||
interface PropertyNamesParams {
|
||||
propertyName: string;
|
||||
}
|
||||
|
||||
interface IfParams {
|
||||
failingKeyword: string;
|
||||
}
|
||||
|
||||
interface SwitchParams {
|
||||
caseIndex: number;
|
||||
}
|
||||
|
||||
interface NoParams { }
|
||||
|
||||
interface EnumParams {
|
||||
allowedValues: Array<any>;
|
||||
}
|
||||
}
|
||||
|
||||
export = ajv;
|
||||
506
electron/node_modules/ajv/lib/ajv.js
generated
vendored
506
electron/node_modules/ajv/lib/ajv.js
generated
vendored
|
|
@ -1,506 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var compileSchema = require('./compile')
|
||||
, resolve = require('./compile/resolve')
|
||||
, Cache = require('./cache')
|
||||
, SchemaObject = require('./compile/schema_obj')
|
||||
, stableStringify = require('fast-json-stable-stringify')
|
||||
, formats = require('./compile/formats')
|
||||
, rules = require('./compile/rules')
|
||||
, $dataMetaSchema = require('./data')
|
||||
, util = require('./compile/util');
|
||||
|
||||
module.exports = Ajv;
|
||||
|
||||
Ajv.prototype.validate = validate;
|
||||
Ajv.prototype.compile = compile;
|
||||
Ajv.prototype.addSchema = addSchema;
|
||||
Ajv.prototype.addMetaSchema = addMetaSchema;
|
||||
Ajv.prototype.validateSchema = validateSchema;
|
||||
Ajv.prototype.getSchema = getSchema;
|
||||
Ajv.prototype.removeSchema = removeSchema;
|
||||
Ajv.prototype.addFormat = addFormat;
|
||||
Ajv.prototype.errorsText = errorsText;
|
||||
|
||||
Ajv.prototype._addSchema = _addSchema;
|
||||
Ajv.prototype._compile = _compile;
|
||||
|
||||
Ajv.prototype.compileAsync = require('./compile/async');
|
||||
var customKeyword = require('./keyword');
|
||||
Ajv.prototype.addKeyword = customKeyword.add;
|
||||
Ajv.prototype.getKeyword = customKeyword.get;
|
||||
Ajv.prototype.removeKeyword = customKeyword.remove;
|
||||
Ajv.prototype.validateKeyword = customKeyword.validate;
|
||||
|
||||
var errorClasses = require('./compile/error_classes');
|
||||
Ajv.ValidationError = errorClasses.Validation;
|
||||
Ajv.MissingRefError = errorClasses.MissingRef;
|
||||
Ajv.$dataMetaSchema = $dataMetaSchema;
|
||||
|
||||
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
|
||||
|
||||
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
|
||||
var META_SUPPORT_DATA = ['/properties'];
|
||||
|
||||
/**
|
||||
* Creates validator instance.
|
||||
* Usage: `Ajv(opts)`
|
||||
* @param {Object} opts optional options
|
||||
* @return {Object} ajv instance
|
||||
*/
|
||||
function Ajv(opts) {
|
||||
if (!(this instanceof Ajv)) return new Ajv(opts);
|
||||
opts = this._opts = util.copy(opts) || {};
|
||||
setLogger(this);
|
||||
this._schemas = {};
|
||||
this._refs = {};
|
||||
this._fragments = {};
|
||||
this._formats = formats(opts.format);
|
||||
|
||||
this._cache = opts.cache || new Cache;
|
||||
this._loadingSchemas = {};
|
||||
this._compilations = [];
|
||||
this.RULES = rules();
|
||||
this._getId = chooseGetId(opts);
|
||||
|
||||
opts.loopRequired = opts.loopRequired || Infinity;
|
||||
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
|
||||
if (opts.serialize === undefined) opts.serialize = stableStringify;
|
||||
this._metaOpts = getMetaSchemaOptions(this);
|
||||
|
||||
if (opts.formats) addInitialFormats(this);
|
||||
if (opts.keywords) addInitialKeywords(this);
|
||||
addDefaultMetaSchema(this);
|
||||
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
|
||||
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
|
||||
addInitialSchemas(this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Validate data using schema
|
||||
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
|
||||
* @this Ajv
|
||||
* @param {String|Object} schemaKeyRef key, ref or schema object
|
||||
* @param {Any} data to be validated
|
||||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
|
||||
*/
|
||||
function validate(schemaKeyRef, data) {
|
||||
var v;
|
||||
if (typeof schemaKeyRef == 'string') {
|
||||
v = this.getSchema(schemaKeyRef);
|
||||
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
|
||||
} else {
|
||||
var schemaObj = this._addSchema(schemaKeyRef);
|
||||
v = schemaObj.validate || this._compile(schemaObj);
|
||||
}
|
||||
|
||||
var valid = v(data);
|
||||
if (v.$async !== true) this.errors = v.errors;
|
||||
return valid;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create validating function for passed schema.
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
|
||||
* @return {Function} validating function
|
||||
*/
|
||||
function compile(schema, _meta) {
|
||||
var schemaObj = this._addSchema(schema, undefined, _meta);
|
||||
return schemaObj.validate || this._compile(schemaObj);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds schema to the instance.
|
||||
* @this Ajv
|
||||
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
|
||||
* @param {String} key 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`.
|
||||
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
|
||||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addSchema(schema, key, _skipValidation, _meta) {
|
||||
if (Array.isArray(schema)){
|
||||
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
|
||||
return this;
|
||||
}
|
||||
var id = this._getId(schema);
|
||||
if (id !== undefined && typeof id != 'string')
|
||||
throw new Error('schema id must be string');
|
||||
key = resolve.normalizeId(key || id);
|
||||
checkUnique(this, key);
|
||||
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add schema that will be used to validate other schemas
|
||||
* options in META_IGNORE_OPTIONS are alway set to false
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {String} key optional schema key
|
||||
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addMetaSchema(schema, key, skipValidation) {
|
||||
this.addSchema(schema, key, skipValidation, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate schema
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to validate
|
||||
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
|
||||
* @return {Boolean} true if schema is valid
|
||||
*/
|
||||
function validateSchema(schema, throwOrLogError) {
|
||||
var $schema = schema.$schema;
|
||||
if ($schema !== undefined && typeof $schema != 'string')
|
||||
throw new Error('$schema must be a string');
|
||||
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
|
||||
if (!$schema) {
|
||||
this.logger.warn('meta-schema not available');
|
||||
this.errors = null;
|
||||
return true;
|
||||
}
|
||||
var valid = this.validate($schema, schema);
|
||||
if (!valid && throwOrLogError) {
|
||||
var message = 'schema is invalid: ' + this.errorsText();
|
||||
if (this._opts.validateSchema == 'log') this.logger.error(message);
|
||||
else throw new Error(message);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
|
||||
function defaultMeta(self) {
|
||||
var meta = self._opts.meta;
|
||||
self._opts.defaultMeta = typeof meta == 'object'
|
||||
? self._getId(meta) || meta
|
||||
: self.getSchema(META_SCHEMA_ID)
|
||||
? META_SCHEMA_ID
|
||||
: undefined;
|
||||
return self._opts.defaultMeta;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get compiled schema from the instance by `key` or `ref`.
|
||||
* @this Ajv
|
||||
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
|
||||
* @return {Function} schema validating function (with property `schema`).
|
||||
*/
|
||||
function getSchema(keyRef) {
|
||||
var schemaObj = _getSchemaObj(this, keyRef);
|
||||
switch (typeof schemaObj) {
|
||||
case 'object': return schemaObj.validate || this._compile(schemaObj);
|
||||
case 'string': return this.getSchema(schemaObj);
|
||||
case 'undefined': return _getSchemaFragment(this, keyRef);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _getSchemaFragment(self, ref) {
|
||||
var res = resolve.schema.call(self, { schema: {} }, ref);
|
||||
if (res) {
|
||||
var schema = res.schema
|
||||
, root = res.root
|
||||
, baseId = res.baseId;
|
||||
var v = compileSchema.call(self, schema, root, undefined, baseId);
|
||||
self._fragments[ref] = new SchemaObject({
|
||||
ref: ref,
|
||||
fragment: true,
|
||||
schema: schema,
|
||||
root: root,
|
||||
baseId: baseId,
|
||||
validate: v
|
||||
});
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _getSchemaObj(self, keyRef) {
|
||||
keyRef = resolve.normalizeId(keyRef);
|
||||
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @this Ajv
|
||||
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function removeSchema(schemaKeyRef) {
|
||||
if (schemaKeyRef instanceof RegExp) {
|
||||
_removeAllSchemas(this, this._schemas, schemaKeyRef);
|
||||
_removeAllSchemas(this, this._refs, schemaKeyRef);
|
||||
return this;
|
||||
}
|
||||
switch (typeof schemaKeyRef) {
|
||||
case 'undefined':
|
||||
_removeAllSchemas(this, this._schemas);
|
||||
_removeAllSchemas(this, this._refs);
|
||||
this._cache.clear();
|
||||
return this;
|
||||
case 'string':
|
||||
var schemaObj = _getSchemaObj(this, schemaKeyRef);
|
||||
if (schemaObj) this._cache.del(schemaObj.cacheKey);
|
||||
delete this._schemas[schemaKeyRef];
|
||||
delete this._refs[schemaKeyRef];
|
||||
return this;
|
||||
case 'object':
|
||||
var serialize = this._opts.serialize;
|
||||
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
|
||||
this._cache.del(cacheKey);
|
||||
var id = this._getId(schemaKeyRef);
|
||||
if (id) {
|
||||
id = resolve.normalizeId(id);
|
||||
delete this._schemas[id];
|
||||
delete this._refs[id];
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
function _removeAllSchemas(self, schemas, regex) {
|
||||
for (var keyRef in schemas) {
|
||||
var schemaObj = schemas[keyRef];
|
||||
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
|
||||
self._cache.del(schemaObj.cacheKey);
|
||||
delete schemas[keyRef];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
|
||||
if (typeof schema != 'object' && typeof schema != 'boolean')
|
||||
throw new Error('schema should be object or boolean');
|
||||
var serialize = this._opts.serialize;
|
||||
var cacheKey = serialize ? serialize(schema) : schema;
|
||||
var cached = this._cache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
|
||||
|
||||
var id = resolve.normalizeId(this._getId(schema));
|
||||
if (id && shouldAddSchema) checkUnique(this, id);
|
||||
|
||||
var willValidate = this._opts.validateSchema !== false && !skipValidation;
|
||||
var recursiveMeta;
|
||||
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
|
||||
this.validateSchema(schema, true);
|
||||
|
||||
var localRefs = resolve.ids.call(this, schema);
|
||||
|
||||
var schemaObj = new SchemaObject({
|
||||
id: id,
|
||||
schema: schema,
|
||||
localRefs: localRefs,
|
||||
cacheKey: cacheKey,
|
||||
meta: meta
|
||||
});
|
||||
|
||||
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
|
||||
this._cache.put(cacheKey, schemaObj);
|
||||
|
||||
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
|
||||
|
||||
return schemaObj;
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function _compile(schemaObj, root) {
|
||||
if (schemaObj.compiling) {
|
||||
schemaObj.validate = callValidate;
|
||||
callValidate.schema = schemaObj.schema;
|
||||
callValidate.errors = null;
|
||||
callValidate.root = root ? root : callValidate;
|
||||
if (schemaObj.schema.$async === true)
|
||||
callValidate.$async = true;
|
||||
return callValidate;
|
||||
}
|
||||
schemaObj.compiling = true;
|
||||
|
||||
var currentOpts;
|
||||
if (schemaObj.meta) {
|
||||
currentOpts = this._opts;
|
||||
this._opts = this._metaOpts;
|
||||
}
|
||||
|
||||
var v;
|
||||
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
|
||||
catch(e) {
|
||||
delete schemaObj.validate;
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
schemaObj.compiling = false;
|
||||
if (schemaObj.meta) this._opts = currentOpts;
|
||||
}
|
||||
|
||||
schemaObj.validate = v;
|
||||
schemaObj.refs = v.refs;
|
||||
schemaObj.refVal = v.refVal;
|
||||
schemaObj.root = v.root;
|
||||
return v;
|
||||
|
||||
|
||||
/* @this {*} - custom context, see passContext option */
|
||||
function callValidate() {
|
||||
/* jshint validthis: true */
|
||||
var _validate = schemaObj.validate;
|
||||
var result = _validate.apply(this, arguments);
|
||||
callValidate.errors = _validate.errors;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function chooseGetId(opts) {
|
||||
switch (opts.schemaId) {
|
||||
case 'auto': return _get$IdOrId;
|
||||
case 'id': return _getId;
|
||||
default: return _get$Id;
|
||||
}
|
||||
}
|
||||
|
||||
/* @this Ajv */
|
||||
function _getId(schema) {
|
||||
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
|
||||
return schema.id;
|
||||
}
|
||||
|
||||
/* @this Ajv */
|
||||
function _get$Id(schema) {
|
||||
if (schema.id) this.logger.warn('schema id ignored', schema.id);
|
||||
return schema.$id;
|
||||
}
|
||||
|
||||
|
||||
function _get$IdOrId(schema) {
|
||||
if (schema.$id && schema.id && schema.$id != schema.id)
|
||||
throw new Error('schema $id is different from id');
|
||||
return schema.$id || schema.id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert array of error message objects to string
|
||||
* @this Ajv
|
||||
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
|
||||
* @param {Object} options optional options with properties `separator` and `dataVar`.
|
||||
* @return {String} human readable string with all errors descriptions
|
||||
*/
|
||||
function errorsText(errors, options) {
|
||||
errors = errors || this.errors;
|
||||
if (!errors) return 'No errors';
|
||||
options = options || {};
|
||||
var separator = options.separator === undefined ? ', ' : options.separator;
|
||||
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
|
||||
|
||||
var text = '';
|
||||
for (var i=0; i<errors.length; i++) {
|
||||
var e = errors[i];
|
||||
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
|
||||
}
|
||||
return text.slice(0, -separator.length);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add custom format
|
||||
* @this Ajv
|
||||
* @param {String} name format name
|
||||
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addFormat(name, format) {
|
||||
if (typeof format == 'string') format = new RegExp(format);
|
||||
this._formats[name] = format;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
function addDefaultMetaSchema(self) {
|
||||
var $dataSchema;
|
||||
if (self._opts.$data) {
|
||||
$dataSchema = require('./refs/data.json');
|
||||
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
|
||||
}
|
||||
if (self._opts.meta === false) return;
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
|
||||
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
|
||||
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
|
||||
}
|
||||
|
||||
|
||||
function addInitialSchemas(self) {
|
||||
var optsSchemas = self._opts.schemas;
|
||||
if (!optsSchemas) return;
|
||||
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
|
||||
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
|
||||
}
|
||||
|
||||
|
||||
function addInitialFormats(self) {
|
||||
for (var name in self._opts.formats) {
|
||||
var format = self._opts.formats[name];
|
||||
self.addFormat(name, format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function addInitialKeywords(self) {
|
||||
for (var name in self._opts.keywords) {
|
||||
var keyword = self._opts.keywords[name];
|
||||
self.addKeyword(name, keyword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkUnique(self, id) {
|
||||
if (self._schemas[id] || self._refs[id])
|
||||
throw new Error('schema with key or id "' + id + '" already exists');
|
||||
}
|
||||
|
||||
|
||||
function getMetaSchemaOptions(self) {
|
||||
var metaOpts = util.copy(self._opts);
|
||||
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
|
||||
delete metaOpts[META_IGNORE_OPTIONS[i]];
|
||||
return metaOpts;
|
||||
}
|
||||
|
||||
|
||||
function setLogger(self) {
|
||||
var logger = self._opts.logger;
|
||||
if (logger === false) {
|
||||
self.logger = {log: noop, warn: noop, error: noop};
|
||||
} else {
|
||||
if (logger === undefined) logger = console;
|
||||
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
|
||||
throw new Error('logger must implement log, warn and error methods');
|
||||
self.logger = logger;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function noop() {}
|
||||
70
electron/node_modules/ajv/lib/ajv.ts
generated
vendored
Normal file
70
electron/node_modules/ajv/lib/ajv.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import type {AnySchemaObject} from "./types"
|
||||
import AjvCore from "./core"
|
||||
import draft7Vocabularies from "./vocabularies/draft7"
|
||||
import discriminator from "./vocabularies/discriminator"
|
||||
import * as draft7MetaSchema from "./refs/json-schema-draft-07.json"
|
||||
|
||||
const META_SUPPORT_DATA = ["/properties"]
|
||||
|
||||
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"
|
||||
|
||||
export 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))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = exports = Ajv
|
||||
module.exports.Ajv = Ajv
|
||||
Object.defineProperty(exports, "__esModule", {value: true})
|
||||
|
||||
export default Ajv
|
||||
|
||||
export {
|
||||
Format,
|
||||
FormatDefinition,
|
||||
AsyncFormatDefinition,
|
||||
KeywordDefinition,
|
||||
KeywordErrorDefinition,
|
||||
CodeKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
Vocabulary,
|
||||
Schema,
|
||||
SchemaObject,
|
||||
AnySchemaObject,
|
||||
AsyncSchema,
|
||||
AnySchema,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
SchemaValidateFunction,
|
||||
ErrorObject,
|
||||
ErrorNoParams,
|
||||
} from "./types"
|
||||
|
||||
export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
|
||||
export {SchemaCxt, SchemaObjCxt} from "./compile"
|
||||
export {KeywordCxt} from "./compile/validate"
|
||||
export {DefinedError} from "./vocabularies/errors"
|
||||
export {JSONType} from "./compile/rules"
|
||||
export {JSONSchemaType} from "./types/json-schema"
|
||||
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
|
||||
export {default as ValidationError} from "./runtime/validation_error"
|
||||
export {default as MissingRefError} from "./compile/ref_error"
|
||||
26
electron/node_modules/ajv/lib/cache.js
generated
vendored
26
electron/node_modules/ajv/lib/cache.js
generated
vendored
|
|
@ -1,26 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
|
||||
var Cache = module.exports = function Cache() {
|
||||
this._cache = {};
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.put = function Cache_put(key, value) {
|
||||
this._cache[key] = value;
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.get = function Cache_get(key) {
|
||||
return this._cache[key];
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.del = function Cache_del(key) {
|
||||
delete this._cache[key];
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.clear = function Cache_clear() {
|
||||
this._cache = {};
|
||||
};
|
||||
90
electron/node_modules/ajv/lib/compile/async.js
generated
vendored
90
electron/node_modules/ajv/lib/compile/async.js
generated
vendored
|
|
@ -1,90 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var MissingRefError = require('./error_classes').MissingRef;
|
||||
|
||||
module.exports = compileAsync;
|
||||
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
|
||||
* @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) {
|
||||
/* eslint no-shadow: 0 */
|
||||
/* global Promise */
|
||||
/* jshint validthis: true */
|
||||
var self = this;
|
||||
if (typeof this._opts.loadSchema != 'function')
|
||||
throw new Error('options.loadSchema should be a function');
|
||||
|
||||
if (typeof meta == 'function') {
|
||||
callback = meta;
|
||||
meta = undefined;
|
||||
}
|
||||
|
||||
var p = loadMetaSchemaOf(schema).then(function () {
|
||||
var schemaObj = self._addSchema(schema, undefined, meta);
|
||||
return schemaObj.validate || _compileAsync(schemaObj);
|
||||
});
|
||||
|
||||
if (callback) {
|
||||
p.then(
|
||||
function(v) { callback(null, v); },
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
return p;
|
||||
|
||||
|
||||
function loadMetaSchemaOf(sch) {
|
||||
var $schema = sch.$schema;
|
||||
return $schema && !self.getSchema($schema)
|
||||
? compileAsync.call(self, { $ref: $schema }, true)
|
||||
: Promise.resolve();
|
||||
}
|
||||
|
||||
|
||||
function _compileAsync(schemaObj) {
|
||||
try { return self._compile(schemaObj); }
|
||||
catch(e) {
|
||||
if (e instanceof MissingRefError) return loadMissingSchema(e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
|
||||
function loadMissingSchema(e) {
|
||||
var ref = e.missingSchema;
|
||||
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
|
||||
|
||||
var schemaPromise = self._loadingSchemas[ref];
|
||||
if (!schemaPromise) {
|
||||
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
|
||||
schemaPromise.then(removePromise, removePromise);
|
||||
}
|
||||
|
||||
return schemaPromise.then(function (sch) {
|
||||
if (!added(ref)) {
|
||||
return loadMetaSchemaOf(sch).then(function () {
|
||||
if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
|
||||
});
|
||||
}
|
||||
}).then(function() {
|
||||
return _compileAsync(schemaObj);
|
||||
});
|
||||
|
||||
function removePromise() {
|
||||
delete self._loadingSchemas[ref];
|
||||
}
|
||||
|
||||
function added(ref) {
|
||||
return self._refs[ref] || self._schemas[ref];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
169
electron/node_modules/ajv/lib/compile/codegen/code.ts
generated
vendored
Normal file
169
electron/node_modules/ajv/lib/compile/codegen/code.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
|
||||
export abstract class _CodeOrName {
|
||||
abstract readonly str: string
|
||||
abstract readonly names: UsedNames
|
||||
abstract toString(): string
|
||||
abstract emptyStr(): boolean
|
||||
}
|
||||
|
||||
export const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i
|
||||
|
||||
export 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}
|
||||
}
|
||||
}
|
||||
|
||||
export class _Code extends _CodeOrName {
|
||||
readonly _items: readonly CodeItem[]
|
||||
private _str?: string
|
||||
private _names?: UsedNames
|
||||
|
||||
constructor(code: string | readonly CodeItem[]) {
|
||||
super()
|
||||
this._items = typeof code === "string" ? [code] : code
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return this.str
|
||||
}
|
||||
|
||||
emptyStr(): boolean {
|
||||
if (this._items.length > 1) return false
|
||||
const item = this._items[0]
|
||||
return item === "" || item === '""'
|
||||
}
|
||||
|
||||
get str(): string {
|
||||
return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, ""))
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return (this._names ??= this._items.reduce((names: UsedNames, c) => {
|
||||
if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1
|
||||
return names
|
||||
}, {}))
|
||||
}
|
||||
}
|
||||
|
||||
export type CodeItem = Name | string | number | boolean | null
|
||||
|
||||
export type UsedNames = Record<string, number | undefined>
|
||||
|
||||
export type Code = _Code | Name
|
||||
|
||||
export type SafeExpr = Code | number | boolean | null
|
||||
|
||||
export const nil = new _Code("")
|
||||
|
||||
type CodeArg = SafeExpr | string | undefined
|
||||
|
||||
export function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {
|
||||
const code: CodeItem[] = [strs[0]]
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
addCodeArg(code, args[i])
|
||||
code.push(strs[++i])
|
||||
}
|
||||
return new _Code(code)
|
||||
}
|
||||
|
||||
const plus = new _Code("+")
|
||||
|
||||
export function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {
|
||||
const expr: CodeItem[] = [safeStringify(strs[0])]
|
||||
let i = 0
|
||||
while (i < args.length) {
|
||||
expr.push(plus)
|
||||
addCodeArg(expr, args[i])
|
||||
expr.push(plus, safeStringify(strs[++i]))
|
||||
}
|
||||
optimize(expr)
|
||||
return new _Code(expr)
|
||||
}
|
||||
|
||||
export function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {
|
||||
if (arg instanceof _Code) code.push(...arg._items)
|
||||
else if (arg instanceof Name) code.push(arg)
|
||||
else code.push(interpolate(arg))
|
||||
}
|
||||
|
||||
function optimize(expr: CodeItem[]): void {
|
||||
let i = 1
|
||||
while (i < expr.length - 1) {
|
||||
if (expr[i] === plus) {
|
||||
const res = mergeExprItems(expr[i - 1], expr[i + 1])
|
||||
if (res !== undefined) {
|
||||
expr.splice(i - 1, 3, res)
|
||||
continue
|
||||
}
|
||||
expr[i++] = "+"
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {
|
||||
if (b === '""') return a
|
||||
if (a === '""') return b
|
||||
if (typeof a == "string") {
|
||||
if (b instanceof Name || a[a.length - 1] !== '"') return
|
||||
if (typeof b != "string") return `${a.slice(0, -1)}${b}"`
|
||||
if (b[0] === '"') return a.slice(0, -1) + b.slice(1)
|
||||
return
|
||||
}
|
||||
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`
|
||||
return
|
||||
}
|
||||
|
||||
export function strConcat(c1: Code, c2: Code): Code {
|
||||
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`
|
||||
}
|
||||
|
||||
// TODO do not allow arrays here
|
||||
function interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {
|
||||
return typeof x == "number" || typeof x == "boolean" || x === null
|
||||
? x
|
||||
: safeStringify(Array.isArray(x) ? x.join(",") : x)
|
||||
}
|
||||
|
||||
export function stringify(x: unknown): Code {
|
||||
return new _Code(safeStringify(x))
|
||||
}
|
||||
|
||||
export function safeStringify(x: unknown): string {
|
||||
return JSON.stringify(x)
|
||||
.replace(/\u2028/g, "\\u2028")
|
||||
.replace(/\u2029/g, "\\u2029")
|
||||
}
|
||||
|
||||
export function getProperty(key: Code | string | number): Code {
|
||||
return typeof key == "string" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`
|
||||
}
|
||||
|
||||
//Does best effort to format the name properly
|
||||
export function getEsmExportName(key: Code | string | number): Code {
|
||||
if (typeof key == "string" && IDENTIFIER.test(key)) {
|
||||
return new _Code(`${key}`)
|
||||
}
|
||||
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)
|
||||
}
|
||||
|
||||
export function regexpCode(rx: RegExp): Code {
|
||||
return new _Code(rx.toString())
|
||||
}
|
||||
852
electron/node_modules/ajv/lib/compile/codegen/index.ts
generated
vendored
Normal file
852
electron/node_modules/ajv/lib/compile/codegen/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,852 @@
|
|||
import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope"
|
||||
import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code"
|
||||
import {Scope, varKinds} from "./scope"
|
||||
|
||||
export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
|
||||
export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"
|
||||
|
||||
// type for expressions that can be safely inserted in code without quotes
|
||||
export type SafeExpr = Code | number | boolean | null
|
||||
|
||||
// type that is either Code of function that adds code to CodeGen instance using its methods
|
||||
export type Block = Code | (() => void)
|
||||
|
||||
export const operators = {
|
||||
GT: new _Code(">"),
|
||||
GTE: new _Code(">="),
|
||||
LT: new _Code("<"),
|
||||
LTE: new _Code("<="),
|
||||
EQ: new _Code("==="),
|
||||
NEQ: new _Code("!=="),
|
||||
NOT: new _Code("!"),
|
||||
OR: new _Code("||"),
|
||||
AND: new _Code("&&"),
|
||||
ADD: new _Code("+"),
|
||||
}
|
||||
|
||||
abstract class Node {
|
||||
abstract readonly names: UsedNames
|
||||
|
||||
optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
|
||||
return this
|
||||
}
|
||||
|
||||
optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
|
||||
return this
|
||||
}
|
||||
|
||||
// get count(): number {
|
||||
// return 1
|
||||
// }
|
||||
}
|
||||
|
||||
class Def extends Node {
|
||||
constructor(
|
||||
private readonly varKind: Name,
|
||||
private readonly name: Name,
|
||||
private rhs?: SafeExpr
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({es5, _n}: CGOptions): string {
|
||||
const varKind = es5 ? varKinds.var : this.varKind
|
||||
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`
|
||||
return `${varKind} ${this.name}${rhs};` + _n
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
if (!names[this.name.str]) return
|
||||
if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
|
||||
}
|
||||
}
|
||||
|
||||
class Assign extends Node {
|
||||
constructor(
|
||||
readonly lhs: Code,
|
||||
public rhs: SafeExpr,
|
||||
private readonly sideEffects?: boolean
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
return `${this.lhs} = ${this.rhs};` + _n
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return
|
||||
this.rhs = optimizeExpr(this.rhs, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
|
||||
return addExprNames(names, this.rhs)
|
||||
}
|
||||
}
|
||||
|
||||
class AssignOp extends Assign {
|
||||
constructor(
|
||||
lhs: Code,
|
||||
private readonly op: Code,
|
||||
rhs: SafeExpr,
|
||||
sideEffects?: boolean
|
||||
) {
|
||||
super(lhs, rhs, sideEffects)
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
return `${this.lhs} ${this.op}= ${this.rhs};` + _n
|
||||
}
|
||||
}
|
||||
|
||||
class Label extends Node {
|
||||
readonly names: UsedNames = {}
|
||||
constructor(readonly label: Name) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
return `${this.label}:` + _n
|
||||
}
|
||||
}
|
||||
|
||||
class Break extends Node {
|
||||
readonly names: UsedNames = {}
|
||||
constructor(readonly label?: Code) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
const label = this.label ? ` ${this.label}` : ""
|
||||
return `break${label};` + _n
|
||||
}
|
||||
}
|
||||
|
||||
class Throw extends Node {
|
||||
constructor(readonly error: Code) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
return `throw ${this.error};` + _n
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return this.error.names
|
||||
}
|
||||
}
|
||||
|
||||
class AnyCode extends Node {
|
||||
constructor(private code: SafeExpr) {
|
||||
super()
|
||||
}
|
||||
|
||||
render({_n}: CGOptions): string {
|
||||
return `${this.code};` + _n
|
||||
}
|
||||
|
||||
optimizeNodes(): this | undefined {
|
||||
return `${this.code}` ? this : undefined
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this {
|
||||
this.code = optimizeExpr(this.code, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return this.code instanceof _CodeOrName ? this.code.names : {}
|
||||
}
|
||||
}
|
||||
|
||||
abstract class ParentNode extends Node {
|
||||
constructor(readonly nodes: ChildNode[] = []) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
return this.nodes.reduce((code, n) => code + n.render(opts), "")
|
||||
}
|
||||
|
||||
optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
|
||||
const {nodes} = this
|
||||
let i = nodes.length
|
||||
while (i--) {
|
||||
const n = nodes[i].optimizeNodes()
|
||||
if (Array.isArray(n)) nodes.splice(i, 1, ...n)
|
||||
else if (n) nodes[i] = n
|
||||
else nodes.splice(i, 1)
|
||||
}
|
||||
return nodes.length > 0 ? this : undefined
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
const {nodes} = this
|
||||
let i = nodes.length
|
||||
while (i--) {
|
||||
// iterating backwards improves 1-pass optimization
|
||||
const n = nodes[i]
|
||||
if (n.optimizeNames(names, constants)) continue
|
||||
subtractNames(names, n.names)
|
||||
nodes.splice(i, 1)
|
||||
}
|
||||
return nodes.length > 0 ? this : undefined
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
|
||||
}
|
||||
|
||||
// get count(): number {
|
||||
// return this.nodes.reduce((c, n) => c + n.count, 1)
|
||||
// }
|
||||
}
|
||||
|
||||
abstract class BlockNode extends ParentNode {
|
||||
render(opts: CGOptions): string {
|
||||
return "{" + opts._n + super.render(opts) + "}" + opts._n
|
||||
}
|
||||
}
|
||||
|
||||
class Root extends ParentNode {}
|
||||
|
||||
class Else extends BlockNode {
|
||||
static readonly kind = "else"
|
||||
}
|
||||
|
||||
class If extends BlockNode {
|
||||
static readonly kind = "if"
|
||||
else?: If | Else
|
||||
constructor(
|
||||
private condition: Code | boolean,
|
||||
nodes?: ChildNode[]
|
||||
) {
|
||||
super(nodes)
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
let code = `if(${this.condition})` + super.render(opts)
|
||||
if (this.else) code += "else " + this.else.render(opts)
|
||||
return code
|
||||
}
|
||||
|
||||
optimizeNodes(): If | ChildNode[] | undefined {
|
||||
super.optimizeNodes()
|
||||
const cond = this.condition
|
||||
if (cond === true) return this.nodes // else is ignored here
|
||||
let e = this.else
|
||||
if (e) {
|
||||
const ns = e.optimizeNodes()
|
||||
e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
|
||||
}
|
||||
if (e) {
|
||||
if (cond === false) return e instanceof If ? e : e.nodes
|
||||
if (this.nodes.length) return this
|
||||
return new If(not(cond), e instanceof If ? [e] : e.nodes)
|
||||
}
|
||||
if (cond === false || !this.nodes.length) return undefined
|
||||
return this
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
this.else = this.else?.optimizeNames(names, constants)
|
||||
if (!(super.optimizeNames(names, constants) || this.else)) return
|
||||
this.condition = optimizeExpr(this.condition, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
const names = super.names
|
||||
addExprNames(names, this.condition)
|
||||
if (this.else) addNames(names, this.else.names)
|
||||
return names
|
||||
}
|
||||
|
||||
// get count(): number {
|
||||
// return super.count + (this.else?.count || 0)
|
||||
// }
|
||||
}
|
||||
|
||||
abstract class For extends BlockNode {
|
||||
static readonly kind = "for"
|
||||
}
|
||||
|
||||
class ForLoop extends For {
|
||||
constructor(private iteration: Code) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
return `for(${this.iteration})` + super.render(opts)
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
if (!super.optimizeNames(names, constants)) return
|
||||
this.iteration = optimizeExpr(this.iteration, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return addNames(super.names, this.iteration.names)
|
||||
}
|
||||
}
|
||||
|
||||
class ForRange extends For {
|
||||
constructor(
|
||||
private readonly varKind: Name,
|
||||
private readonly name: Name,
|
||||
private readonly from: SafeExpr,
|
||||
private readonly to: SafeExpr
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
const varKind = opts.es5 ? varKinds.var : this.varKind
|
||||
const {name, from, to} = this
|
||||
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
const names = addExprNames(super.names, this.from)
|
||||
return addExprNames(names, this.to)
|
||||
}
|
||||
}
|
||||
|
||||
class ForIter extends For {
|
||||
constructor(
|
||||
private readonly loop: "of" | "in",
|
||||
private readonly varKind: Name,
|
||||
private readonly name: Name,
|
||||
private iterable: Code
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
||||
if (!super.optimizeNames(names, constants)) return
|
||||
this.iterable = optimizeExpr(this.iterable, names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
return addNames(super.names, this.iterable.names)
|
||||
}
|
||||
}
|
||||
|
||||
class Func extends BlockNode {
|
||||
static readonly kind = "func"
|
||||
constructor(
|
||||
public name: Name,
|
||||
public args: Code,
|
||||
public async?: boolean
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
const _async = this.async ? "async " : ""
|
||||
return `${_async}function ${this.name}(${this.args})` + super.render(opts)
|
||||
}
|
||||
}
|
||||
|
||||
class Return extends ParentNode {
|
||||
static readonly kind = "return"
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
return "return " + super.render(opts)
|
||||
}
|
||||
}
|
||||
|
||||
class Try extends BlockNode {
|
||||
catch?: Catch
|
||||
finally?: Finally
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
let code = "try" + super.render(opts)
|
||||
if (this.catch) code += this.catch.render(opts)
|
||||
if (this.finally) code += this.finally.render(opts)
|
||||
return code
|
||||
}
|
||||
|
||||
optimizeNodes(): this {
|
||||
super.optimizeNodes()
|
||||
this.catch?.optimizeNodes() as Catch | undefined
|
||||
this.finally?.optimizeNodes() as Finally | undefined
|
||||
return this
|
||||
}
|
||||
|
||||
optimizeNames(names: UsedNames, constants: Constants): this {
|
||||
super.optimizeNames(names, constants)
|
||||
this.catch?.optimizeNames(names, constants)
|
||||
this.finally?.optimizeNames(names, constants)
|
||||
return this
|
||||
}
|
||||
|
||||
get names(): UsedNames {
|
||||
const names = super.names
|
||||
if (this.catch) addNames(names, this.catch.names)
|
||||
if (this.finally) addNames(names, this.finally.names)
|
||||
return names
|
||||
}
|
||||
|
||||
// get count(): number {
|
||||
// return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
|
||||
// }
|
||||
}
|
||||
|
||||
class Catch extends BlockNode {
|
||||
static readonly kind = "catch"
|
||||
constructor(readonly error: Name) {
|
||||
super()
|
||||
}
|
||||
|
||||
render(opts: CGOptions): string {
|
||||
return `catch(${this.error})` + super.render(opts)
|
||||
}
|
||||
}
|
||||
|
||||
class Finally extends BlockNode {
|
||||
static readonly kind = "finally"
|
||||
render(opts: CGOptions): string {
|
||||
return "finally" + super.render(opts)
|
||||
}
|
||||
}
|
||||
|
||||
type StartBlockNode = If | For | Func | Return | Try
|
||||
|
||||
type LeafNode = Def | Assign | Label | Break | Throw | AnyCode
|
||||
|
||||
type ChildNode = StartBlockNode | LeafNode
|
||||
|
||||
type EndBlockNodeType =
|
||||
| typeof If
|
||||
| typeof Else
|
||||
| typeof For
|
||||
| typeof Func
|
||||
| typeof Return
|
||||
| typeof Catch
|
||||
| typeof Finally
|
||||
|
||||
type Constants = Record<string, SafeExpr | undefined>
|
||||
|
||||
export interface CodeGenOptions {
|
||||
es5?: boolean
|
||||
lines?: boolean
|
||||
ownProperties?: boolean
|
||||
}
|
||||
|
||||
interface CGOptions extends CodeGenOptions {
|
||||
_n: "\n" | ""
|
||||
}
|
||||
|
||||
export 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
|
||||
// }
|
||||
}
|
||||
|
||||
function addNames(names: UsedNames, from: UsedNames): UsedNames {
|
||||
for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
|
||||
return names
|
||||
}
|
||||
|
||||
function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
|
||||
return from instanceof _CodeOrName ? addNames(names, from.names) : names
|
||||
}
|
||||
|
||||
function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T
|
||||
function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
|
||||
if (expr instanceof Name) return replaceName(expr)
|
||||
if (!canOptimize(expr)) return expr
|
||||
return new _Code(
|
||||
expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
|
||||
if (c instanceof Name) c = replaceName(c)
|
||||
if (c instanceof _Code) items.push(...c._items)
|
||||
else items.push(c)
|
||||
return items
|
||||
}, [])
|
||||
)
|
||||
|
||||
function replaceName(n: Name): SafeExpr {
|
||||
const c = constants[n.str]
|
||||
if (c === undefined || names[n.str] !== 1) return n
|
||||
delete names[n.str]
|
||||
return c
|
||||
}
|
||||
|
||||
function canOptimize(e: SafeExpr): e is _Code {
|
||||
return (
|
||||
e instanceof _Code &&
|
||||
e._items.some(
|
||||
(c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function subtractNames(names: UsedNames, from: UsedNames): void {
|
||||
for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
|
||||
}
|
||||
|
||||
export function not<T extends Code | SafeExpr>(x: T): T
|
||||
export function not(x: Code | SafeExpr): Code | SafeExpr {
|
||||
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}`
|
||||
}
|
||||
|
||||
const andCode = mappend(operators.AND)
|
||||
|
||||
// boolean AND (&&) expression with the passed arguments
|
||||
export function and(...args: Code[]): Code {
|
||||
return args.reduce(andCode)
|
||||
}
|
||||
|
||||
const orCode = mappend(operators.OR)
|
||||
|
||||
// boolean OR (||) expression with the passed arguments
|
||||
export function or(...args: Code[]): Code {
|
||||
return args.reduce(orCode)
|
||||
}
|
||||
|
||||
type MAppend = (x: Code, y: Code) => Code
|
||||
|
||||
function mappend(op: Code): MAppend {
|
||||
return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
|
||||
}
|
||||
|
||||
function par(x: Code): Code {
|
||||
return x instanceof Name ? x : _`(${x})`
|
||||
}
|
||||
215
electron/node_modules/ajv/lib/compile/codegen/scope.ts
generated
vendored
Normal file
215
electron/node_modules/ajv/lib/compile/codegen/scope.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
import {_, nil, Code, Name} from "./code"
|
||||
|
||||
interface NameGroup {
|
||||
prefix: string
|
||||
index: number
|
||||
}
|
||||
|
||||
export interface NameValue {
|
||||
ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure
|
||||
key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used
|
||||
code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)
|
||||
}
|
||||
|
||||
export type ValueReference = unknown // possibly make CodeGen parameterized type on this type
|
||||
|
||||
class ValueError extends Error {
|
||||
readonly value?: NameValue
|
||||
constructor(name: ValueScopeName) {
|
||||
super(`CodeGen: "code" for ${name} not defined`)
|
||||
this.value = name.value
|
||||
}
|
||||
}
|
||||
|
||||
interface ScopeOptions {
|
||||
prefixes?: Set<string>
|
||||
parent?: Scope
|
||||
}
|
||||
|
||||
interface ValueScopeOptions extends ScopeOptions {
|
||||
scope: ScopeStore
|
||||
es5?: boolean
|
||||
lines?: boolean
|
||||
}
|
||||
|
||||
export type ScopeStore = Record<string, ValueReference[] | undefined>
|
||||
|
||||
type ScopeValues = {
|
||||
[Prefix in string]?: Map<unknown, ValueScopeName>
|
||||
}
|
||||
|
||||
export type ScopeValueSets = {
|
||||
[Prefix in string]?: Set<ValueScopeName>
|
||||
}
|
||||
|
||||
export enum UsedValueState {
|
||||
Started,
|
||||
Completed,
|
||||
}
|
||||
|
||||
export type UsedScopeValues = {
|
||||
[Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>
|
||||
}
|
||||
|
||||
export const varKinds = {
|
||||
const: new Name("const"),
|
||||
let: new Name("let"),
|
||||
var: new Name("var"),
|
||||
}
|
||||
|
||||
export class Scope {
|
||||
protected readonly _names: {[Prefix in string]?: NameGroup} = {}
|
||||
protected readonly _prefixes?: Set<string>
|
||||
protected readonly _parent?: Scope
|
||||
|
||||
constructor({prefixes, parent}: ScopeOptions = {}) {
|
||||
this._prefixes = prefixes
|
||||
this._parent = parent
|
||||
}
|
||||
|
||||
toName(nameOrPrefix: Name | string): Name {
|
||||
return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)
|
||||
}
|
||||
|
||||
name(prefix: string): Name {
|
||||
return new Name(this._newName(prefix))
|
||||
}
|
||||
|
||||
protected _newName(prefix: string): string {
|
||||
const ng = this._names[prefix] || this._nameGroup(prefix)
|
||||
return `${prefix}${ng.index++}`
|
||||
}
|
||||
|
||||
private _nameGroup(prefix: string): NameGroup {
|
||||
if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {
|
||||
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`)
|
||||
}
|
||||
return (this._names[prefix] = {prefix, index: 0})
|
||||
}
|
||||
}
|
||||
|
||||
interface ScopePath {
|
||||
property: string
|
||||
itemIndex: number
|
||||
}
|
||||
|
||||
export class ValueScopeName extends Name {
|
||||
readonly prefix: string
|
||||
value?: NameValue
|
||||
scopePath?: Code
|
||||
|
||||
constructor(prefix: string, nameStr: string) {
|
||||
super(nameStr)
|
||||
this.prefix = prefix
|
||||
}
|
||||
|
||||
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
|
||||
this.value = value
|
||||
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
|
||||
}
|
||||
}
|
||||
|
||||
interface VSOptions extends ValueScopeOptions {
|
||||
_n: Code
|
||||
}
|
||||
|
||||
const line = _`\n`
|
||||
|
||||
export class ValueScope extends Scope {
|
||||
protected readonly _values: ScopeValues = {}
|
||||
protected readonly _scope: ScopeStore
|
||||
readonly opts: VSOptions
|
||||
|
||||
constructor(opts: ValueScopeOptions) {
|
||||
super(opts)
|
||||
this._scope = opts.scope
|
||||
this.opts = {...opts, _n: opts.lines ? line : nil}
|
||||
}
|
||||
|
||||
get(): ScopeStore {
|
||||
return this._scope
|
||||
}
|
||||
|
||||
name(prefix: string): ValueScopeName {
|
||||
return new ValueScopeName(prefix, this._newName(prefix))
|
||||
}
|
||||
|
||||
value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {
|
||||
if (value.ref === undefined) throw new Error("CodeGen: ref must be passed in value")
|
||||
const name = this.toName(nameOrPrefix) as ValueScopeName
|
||||
const {prefix} = name
|
||||
const valueKey = value.key ?? value.ref
|
||||
let vs = this._values[prefix]
|
||||
if (vs) {
|
||||
const _name = vs.get(valueKey)
|
||||
if (_name) return _name
|
||||
} else {
|
||||
vs = this._values[prefix] = new Map()
|
||||
}
|
||||
vs.set(valueKey, name)
|
||||
|
||||
const s = this._scope[prefix] || (this._scope[prefix] = [])
|
||||
const itemIndex = s.length
|
||||
s[itemIndex] = value.ref
|
||||
name.setValue(value, {property: prefix, itemIndex})
|
||||
return name
|
||||
}
|
||||
|
||||
getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
|
||||
const vs = this._values[prefix]
|
||||
if (!vs) return
|
||||
return vs.get(keyOrRef)
|
||||
}
|
||||
|
||||
scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {
|
||||
return this._reduceValues(values, (name: ValueScopeName) => {
|
||||
if (name.scopePath === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
|
||||
return _`${scopeName}${name.scopePath}`
|
||||
})
|
||||
}
|
||||
|
||||
scopeCode(
|
||||
values: ScopeValues | ScopeValueSets = this._values,
|
||||
usedValues?: UsedScopeValues,
|
||||
getCode?: (n: ValueScopeName) => Code | undefined
|
||||
): Code {
|
||||
return this._reduceValues(
|
||||
values,
|
||||
(name: ValueScopeName) => {
|
||||
if (name.value === undefined) throw new Error(`CodeGen: name "${name}" has no value`)
|
||||
return name.value.code
|
||||
},
|
||||
usedValues,
|
||||
getCode
|
||||
)
|
||||
}
|
||||
|
||||
private _reduceValues(
|
||||
values: ScopeValues | ScopeValueSets,
|
||||
valueCode: (n: ValueScopeName) => Code | undefined,
|
||||
usedValues: UsedScopeValues = {},
|
||||
getCode?: (n: ValueScopeName) => Code | undefined
|
||||
): Code {
|
||||
let code: Code = nil
|
||||
for (const prefix in values) {
|
||||
const vs = values[prefix]
|
||||
if (!vs) continue
|
||||
const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())
|
||||
vs.forEach((name: ValueScopeName) => {
|
||||
if (nameSet.has(name)) return
|
||||
nameSet.set(name, UsedValueState.Started)
|
||||
let c = valueCode(name)
|
||||
if (c) {
|
||||
const def = this.opts.es5 ? varKinds.var : varKinds.const
|
||||
code = _`${code}${def} ${name} = ${c};${this.opts._n}`
|
||||
} else if ((c = getCode?.(name))) {
|
||||
code = _`${code}${c}${this.opts._n}`
|
||||
} else {
|
||||
throw new ValueError(name)
|
||||
}
|
||||
nameSet.set(name, UsedValueState.Completed)
|
||||
})
|
||||
}
|
||||
return code
|
||||
}
|
||||
}
|
||||
5
electron/node_modules/ajv/lib/compile/equal.js
generated
vendored
5
electron/node_modules/ajv/lib/compile/equal.js
generated
vendored
|
|
@ -1,5 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
// do NOT remove this file - it would break pre-compiled schemas
|
||||
// https://github.com/ajv-validator/ajv/issues/889
|
||||
module.exports = require('fast-deep-equal');
|
||||
34
electron/node_modules/ajv/lib/compile/error_classes.js
generated
vendored
34
electron/node_modules/ajv/lib/compile/error_classes.js
generated
vendored
|
|
@ -1,34 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var resolve = require('./resolve');
|
||||
|
||||
module.exports = {
|
||||
Validation: errorSubclass(ValidationError),
|
||||
MissingRef: errorSubclass(MissingRefError)
|
||||
};
|
||||
|
||||
|
||||
function ValidationError(errors) {
|
||||
this.message = 'validation failed';
|
||||
this.errors = errors;
|
||||
this.ajv = this.validation = true;
|
||||
}
|
||||
|
||||
|
||||
MissingRefError.message = function (baseId, ref) {
|
||||
return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
|
||||
};
|
||||
|
||||
|
||||
function MissingRefError(baseId, ref, message) {
|
||||
this.message = message || MissingRefError.message(baseId, ref);
|
||||
this.missingRef = resolve.url(baseId, ref);
|
||||
this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
|
||||
}
|
||||
|
||||
|
||||
function errorSubclass(Subclass) {
|
||||
Subclass.prototype = Object.create(Error.prototype);
|
||||
Subclass.prototype.constructor = Subclass;
|
||||
return Subclass;
|
||||
}
|
||||
184
electron/node_modules/ajv/lib/compile/errors.ts
generated
vendored
Normal file
184
electron/node_modules/ajv/lib/compile/errors.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
import type {KeywordErrorCxt, KeywordErrorDefinition} from "../types"
|
||||
import type {SchemaCxt} from "./index"
|
||||
import {CodeGen, _, str, strConcat, Code, Name} from "./codegen"
|
||||
import {SafeExpr} from "./codegen/code"
|
||||
import {getErrorPath, Type} from "./util"
|
||||
import N from "./names"
|
||||
|
||||
export const keywordError: KeywordErrorDefinition = {
|
||||
message: ({keyword}) => str`must pass "${keyword}" keyword validation`,
|
||||
}
|
||||
|
||||
export const keyword$DataError: KeywordErrorDefinition = {
|
||||
message: ({keyword, schemaType}) =>
|
||||
schemaType
|
||||
? str`"${keyword}" keyword must be ${schemaType} ($data)`
|
||||
: str`"${keyword}" keyword is invalid ($data)`,
|
||||
}
|
||||
|
||||
export interface ErrorPaths {
|
||||
instancePath?: Code
|
||||
schemaPath?: string
|
||||
parentSchema?: boolean
|
||||
}
|
||||
|
||||
export 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}]`)
|
||||
}
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
}
|
||||
|
||||
export 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)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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}++`)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
const E = {
|
||||
keyword: new Name("keyword"),
|
||||
schemaPath: new Name("schemaPath"), // also used in JTD errors
|
||||
params: new Name("params"),
|
||||
propertyName: new Name("propertyName"),
|
||||
message: new Name("message"),
|
||||
schema: new Name("schema"),
|
||||
parentSchema: new Name("parentSchema"),
|
||||
}
|
||||
|
||||
function errorObjectCode(
|
||||
cxt: KeywordErrorCxt,
|
||||
error: KeywordErrorDefinition,
|
||||
errorPaths?: ErrorPaths
|
||||
): Code {
|
||||
const {createErrors} = cxt.it
|
||||
if (createErrors === false) return _`{}`
|
||||
return errorObject(cxt, error, errorPaths)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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)]
|
||||
}
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
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])
|
||||
}
|
||||
142
electron/node_modules/ajv/lib/compile/formats.js
generated
vendored
142
electron/node_modules/ajv/lib/compile/formats.js
generated
vendored
|
|
@ -1,142 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
|
||||
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
|
||||
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
|
||||
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
|
||||
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
// uri-template: https://tools.ietf.org/html/rfc6570
|
||||
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
|
||||
// For the source: https://gist.github.com/dperini/729294
|
||||
// For test cases: https://mathiasbynens.be/demo/url-regex
|
||||
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
|
||||
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
|
||||
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
|
||||
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
||||
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
|
||||
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
|
||||
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
|
||||
|
||||
|
||||
module.exports = formats;
|
||||
|
||||
function formats(mode) {
|
||||
mode = mode == 'full' ? 'full' : 'fast';
|
||||
return util.copy(formats[mode], Object.create(null));
|
||||
}
|
||||
|
||||
|
||||
formats.fast = {
|
||||
// date: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
|
||||
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
|
||||
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
|
||||
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
|
||||
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
|
||||
'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
|
||||
'uri-template': URITEMPLATE,
|
||||
url: URL,
|
||||
// email (sources from jsen validator):
|
||||
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
|
||||
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
|
||||
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
|
||||
hostname: HOSTNAME,
|
||||
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
|
||||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
|
||||
// optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
|
||||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
|
||||
regex: regex,
|
||||
// uuid: http://tools.ietf.org/html/rfc4122
|
||||
uuid: UUID,
|
||||
// JSON-pointer: https://tools.ietf.org/html/rfc6901
|
||||
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
|
||||
'json-pointer': JSON_POINTER,
|
||||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
|
||||
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
|
||||
'relative-json-pointer': RELATIVE_JSON_POINTER
|
||||
};
|
||||
|
||||
|
||||
formats.full = {
|
||||
date: date,
|
||||
time: time,
|
||||
'date-time': date_time,
|
||||
uri: uri,
|
||||
'uri-reference': URIREF,
|
||||
'uri-template': URITEMPLATE,
|
||||
url: URL,
|
||||
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
|
||||
hostname: HOSTNAME,
|
||||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
|
||||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
|
||||
regex: regex,
|
||||
uuid: UUID,
|
||||
'json-pointer': JSON_POINTER,
|
||||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
|
||||
'relative-json-pointer': RELATIVE_JSON_POINTER
|
||||
};
|
||||
|
||||
|
||||
function isLeapYear(year) {
|
||||
// https://tools.ietf.org/html/rfc3339#appendix-C
|
||||
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
}
|
||||
|
||||
|
||||
function date(str) {
|
||||
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
var matches = str.match(DATE);
|
||||
if (!matches) return false;
|
||||
|
||||
var year = +matches[1];
|
||||
var month = +matches[2];
|
||||
var day = +matches[3];
|
||||
|
||||
return month >= 1 && month <= 12 && day >= 1 &&
|
||||
day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
|
||||
}
|
||||
|
||||
|
||||
function time(str, full) {
|
||||
var matches = str.match(TIME);
|
||||
if (!matches) return false;
|
||||
|
||||
var hour = matches[1];
|
||||
var minute = matches[2];
|
||||
var second = matches[3];
|
||||
var timeZone = matches[5];
|
||||
return ((hour <= 23 && minute <= 59 && second <= 59) ||
|
||||
(hour == 23 && minute == 59 && second == 60)) &&
|
||||
(!full || timeZone);
|
||||
}
|
||||
|
||||
|
||||
var DATE_TIME_SEPARATOR = /t|\s/i;
|
||||
function date_time(str) {
|
||||
// http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
var dateTime = str.split(DATE_TIME_SEPARATOR);
|
||||
return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
|
||||
}
|
||||
|
||||
|
||||
var NOT_URI_FRAGMENT = /\/|:/;
|
||||
function uri(str) {
|
||||
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
|
||||
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
|
||||
}
|
||||
|
||||
|
||||
var Z_ANCHOR = /[^\\]\\Z/;
|
||||
function regex(str) {
|
||||
if (Z_ANCHOR.test(str)) return false;
|
||||
try {
|
||||
new RegExp(str);
|
||||
return true;
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
389
electron/node_modules/ajv/lib/compile/index.js
generated
vendored
389
electron/node_modules/ajv/lib/compile/index.js
generated
vendored
|
|
@ -1,389 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var resolve = require('./resolve')
|
||||
, util = require('./util')
|
||||
, errorClasses = require('./error_classes')
|
||||
, stableStringify = require('fast-json-stable-stringify');
|
||||
|
||||
var validateGenerator = require('../dotjs/validate');
|
||||
|
||||
/**
|
||||
* Functions below are used inside compiled validations function
|
||||
*/
|
||||
|
||||
var ucs2length = util.ucs2length;
|
||||
var equal = require('fast-deep-equal');
|
||||
|
||||
// this error is thrown by async schemas to return validation errors via exception
|
||||
var ValidationError = errorClasses.Validation;
|
||||
|
||||
module.exports = compile;
|
||||
|
||||
|
||||
/**
|
||||
* Compiles schema to validation function
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Object} root object with information about the root schema for this schema
|
||||
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
|
||||
* @param {String} baseId base ID for IDs in the schema
|
||||
* @return {Function} validation function
|
||||
*/
|
||||
function compile(schema, root, localRefs, baseId) {
|
||||
/* jshint validthis: true, evil: true */
|
||||
/* eslint no-shadow: 0 */
|
||||
var self = this
|
||||
, opts = this._opts
|
||||
, refVal = [ undefined ]
|
||||
, refs = {}
|
||||
, patterns = []
|
||||
, patternsHash = {}
|
||||
, defaults = []
|
||||
, defaultsHash = {}
|
||||
, customRules = [];
|
||||
|
||||
function patternCode(i, patterns) {
|
||||
var regExpCode = opts.regExp ? 'regExp' : 'new RegExp';
|
||||
return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');';
|
||||
}
|
||||
|
||||
root = root || { schema: schema, refVal: refVal, refs: refs };
|
||||
|
||||
var c = checkCompiling.call(this, schema, root, baseId);
|
||||
var compilation = this._compilations[c.index];
|
||||
if (c.compiling) return (compilation.callValidate = callValidate);
|
||||
|
||||
var formats = this._formats;
|
||||
var RULES = this.RULES;
|
||||
|
||||
try {
|
||||
var v = localCompile(schema, root, localRefs, baseId);
|
||||
compilation.validate = v;
|
||||
var cv = compilation.callValidate;
|
||||
if (cv) {
|
||||
cv.schema = v.schema;
|
||||
cv.errors = null;
|
||||
cv.refs = v.refs;
|
||||
cv.refVal = v.refVal;
|
||||
cv.root = v.root;
|
||||
cv.$async = v.$async;
|
||||
if (opts.sourceCode) cv.source = v.source;
|
||||
}
|
||||
return v;
|
||||
} finally {
|
||||
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)
|
||||
return compile.call(self, _schema, _root, localRefs, baseId);
|
||||
|
||||
var $async = _schema.$async === true;
|
||||
|
||||
var sourceCode = validateGenerator({
|
||||
isTop: true,
|
||||
schema: _schema,
|
||||
isRoot: isRoot,
|
||||
baseId: baseId,
|
||||
root: _root,
|
||||
schemaPath: '',
|
||||
errSchemaPath: '#',
|
||||
errorPath: '""',
|
||||
MissingRefError: errorClasses.MissingRef,
|
||||
RULES: RULES,
|
||||
validate: validateGenerator,
|
||||
util: util,
|
||||
resolve: resolve,
|
||||
resolveRef: resolveRef,
|
||||
usePattern: usePattern,
|
||||
useDefault: useDefault,
|
||||
useCustomRule: useCustomRule,
|
||||
opts: opts,
|
||||
formats: formats,
|
||||
logger: self.logger,
|
||||
self: self
|
||||
});
|
||||
|
||||
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
|
||||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
|
||||
+ sourceCode;
|
||||
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
|
||||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
|
||||
var validate;
|
||||
try {
|
||||
var makeValidate = new Function(
|
||||
'self',
|
||||
'RULES',
|
||||
'formats',
|
||||
'root',
|
||||
'refVal',
|
||||
'defaults',
|
||||
'customRules',
|
||||
'equal',
|
||||
'ucs2length',
|
||||
'ValidationError',
|
||||
'regExp',
|
||||
sourceCode
|
||||
);
|
||||
|
||||
validate = makeValidate(
|
||||
self,
|
||||
RULES,
|
||||
formats,
|
||||
root,
|
||||
refVal,
|
||||
defaults,
|
||||
customRules,
|
||||
equal,
|
||||
ucs2length,
|
||||
ValidationError,
|
||||
opts.regExp
|
||||
);
|
||||
|
||||
refVal[0] = validate;
|
||||
} catch(e) {
|
||||
self.logger.error('Error compiling schema, function code:', sourceCode);
|
||||
throw e;
|
||||
}
|
||||
|
||||
validate.schema = _schema;
|
||||
validate.errors = null;
|
||||
validate.refs = refs;
|
||||
validate.refVal = refVal;
|
||||
validate.root = isRoot ? validate : _root;
|
||||
if ($async) validate.$async = true;
|
||||
if (opts.sourceCode === true) {
|
||||
validate.source = {
|
||||
code: sourceCode,
|
||||
patterns: patterns,
|
||||
defaults: defaults
|
||||
};
|
||||
}
|
||||
|
||||
return validate;
|
||||
}
|
||||
|
||||
function resolveRef(baseId, ref, isRoot) {
|
||||
ref = resolve.url(baseId, ref);
|
||||
var refIndex = refs[ref];
|
||||
var _refVal, refCode;
|
||||
if (refIndex !== undefined) {
|
||||
_refVal = refVal[refIndex];
|
||||
refCode = 'refVal[' + refIndex + ']';
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
if (!isRoot && root.refs) {
|
||||
var rootRefId = root.refs[ref];
|
||||
if (rootRefId !== undefined) {
|
||||
_refVal = root.refVal[rootRefId];
|
||||
refCode = addLocalRef(ref, _refVal);
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
refCode = addLocalRef(ref);
|
||||
var v = resolve.call(self, localCompile, root, ref);
|
||||
if (v === undefined) {
|
||||
var localSchema = localRefs && localRefs[ref];
|
||||
if (localSchema) {
|
||||
v = resolve.inlineRef(localSchema, opts.inlineRefs)
|
||||
? localSchema
|
||||
: compile.call(self, localSchema, root, localRefs, baseId);
|
||||
}
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
removeLocalRef(ref);
|
||||
} else {
|
||||
replaceLocalRef(ref, v);
|
||||
return resolvedRef(v, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
function addLocalRef(ref, v) {
|
||||
var refId = refVal.length;
|
||||
refVal[refId] = v;
|
||||
refs[ref] = refId;
|
||||
return 'refVal' + refId;
|
||||
}
|
||||
|
||||
function removeLocalRef(ref) {
|
||||
delete refs[ref];
|
||||
}
|
||||
|
||||
function replaceLocalRef(ref, v) {
|
||||
var refId = refs[ref];
|
||||
refVal[refId] = v;
|
||||
}
|
||||
|
||||
function resolvedRef(refVal, code) {
|
||||
return typeof refVal == 'object' || typeof refVal == 'boolean'
|
||||
? { code: code, schema: refVal, inline: true }
|
||||
: { code: code, $async: refVal && !!refVal.$async };
|
||||
}
|
||||
|
||||
function usePattern(regexStr) {
|
||||
var index = patternsHash[regexStr];
|
||||
if (index === undefined) {
|
||||
index = patternsHash[regexStr] = patterns.length;
|
||||
patterns[index] = regexStr;
|
||||
}
|
||||
return 'pattern' + index;
|
||||
}
|
||||
|
||||
function useDefault(value) {
|
||||
switch (typeof value) {
|
||||
case 'boolean':
|
||||
case 'number':
|
||||
return '' + value;
|
||||
case 'string':
|
||||
return util.toQuotedString(value);
|
||||
case 'object':
|
||||
if (value === null) return 'null';
|
||||
var valueStr = stableStringify(value);
|
||||
var index = defaultsHash[valueStr];
|
||||
if (index === undefined) {
|
||||
index = defaultsHash[valueStr] = defaults.length;
|
||||
defaults[index] = value;
|
||||
}
|
||||
return 'default' + index;
|
||||
}
|
||||
}
|
||||
|
||||
function useCustomRule(rule, schema, parentSchema, it) {
|
||||
if (self._opts.validateSchema !== false) {
|
||||
var deps = rule.definition.dependencies;
|
||||
if (deps && !deps.every(function(keyword) {
|
||||
return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
|
||||
}))
|
||||
throw new Error('parent schema must have all required keywords: ' + deps.join(','));
|
||||
|
||||
var validateSchema = rule.definition.validateSchema;
|
||||
if (validateSchema) {
|
||||
var valid = validateSchema(schema);
|
||||
if (!valid) {
|
||||
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
|
||||
if (self._opts.validateSchema == 'log') self.logger.error(message);
|
||||
else throw new Error(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var compile = rule.definition.compile
|
||||
, inline = rule.definition.inline
|
||||
, macro = rule.definition.macro;
|
||||
|
||||
var validate;
|
||||
if (compile) {
|
||||
validate = compile.call(self, schema, parentSchema, it);
|
||||
} else if (macro) {
|
||||
validate = macro.call(self, schema, parentSchema, it);
|
||||
if (opts.validateSchema !== false) self.validateSchema(validate, true);
|
||||
} else if (inline) {
|
||||
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
|
||||
} else {
|
||||
validate = rule.definition.validate;
|
||||
if (!validate) return;
|
||||
}
|
||||
|
||||
if (validate === undefined)
|
||||
throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
|
||||
|
||||
var index = customRules.length;
|
||||
customRules[index] = validate;
|
||||
|
||||
return {
|
||||
code: 'customRule' + index,
|
||||
validate: validate
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the schema is currently compiled
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
|
||||
*/
|
||||
function checkCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var index = compIndex.call(this, schema, root, baseId);
|
||||
if (index >= 0) return { index: index, compiling: true };
|
||||
index = this._compilations.length;
|
||||
this._compilations[index] = {
|
||||
schema: schema,
|
||||
root: root,
|
||||
baseId: baseId
|
||||
};
|
||||
return { index: index, compiling: false };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the schema from the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
*/
|
||||
function endCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var i = compIndex.call(this, schema, root, baseId);
|
||||
if (i >= 0) this._compilations.splice(i, 1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Index of schema compilation in the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Integer} compilation index
|
||||
*/
|
||||
function compIndex(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
for (var i=0; i<this._compilations.length; i++) {
|
||||
var c = this._compilations[i];
|
||||
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
function defaultCode(i) {
|
||||
return 'var default' + i + ' = defaults[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function refValCode(i, refVal) {
|
||||
return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function customRuleCode(i) {
|
||||
return 'var customRule' + i + ' = customRules[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function vars(arr, statement) {
|
||||
if (!arr.length) return '';
|
||||
var code = '';
|
||||
for (var i=0; i<arr.length; i++)
|
||||
code += statement(i, arr);
|
||||
return code;
|
||||
}
|
||||
324
electron/node_modules/ajv/lib/compile/index.ts
generated
vendored
Normal file
324
electron/node_modules/ajv/lib/compile/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
import type {
|
||||
AnySchema,
|
||||
AnySchemaObject,
|
||||
AnyValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
EvaluatedProperties,
|
||||
EvaluatedItems,
|
||||
} from "../types"
|
||||
import type Ajv from "../core"
|
||||
import type {InstanceOptions} from "../core"
|
||||
import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
|
||||
import ValidationError from "../runtime/validation_error"
|
||||
import N from "./names"
|
||||
import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
|
||||
import {schemaHasRulesButRef, unescapeFragment} from "./util"
|
||||
import {validateFunctionCode} from "./validate"
|
||||
import {URIComponent} from "fast-uri"
|
||||
import {JSONType} from "./rules"
|
||||
|
||||
export type SchemaRefs = {
|
||||
[Ref in string]?: SchemaEnv | AnySchema
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export interface SchemaObjCxt extends SchemaCxt {
|
||||
readonly schema: AnySchemaObject
|
||||
}
|
||||
interface SchemaEnvArgs {
|
||||
readonly schema: AnySchema
|
||||
readonly schemaId?: "$id" | "id"
|
||||
readonly root?: SchemaEnv
|
||||
readonly baseId?: string
|
||||
readonly schemaPath?: string
|
||||
readonly localRefs?: LocalRefs
|
||||
readonly meta?: boolean
|
||||
}
|
||||
|
||||
export 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 = {}
|
||||
}
|
||||
}
|
||||
|
||||
// let codeSize = 0
|
||||
// let nodeCount = 0
|
||||
|
||||
// Compiles schema in SchemaEnv
|
||||
export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
|
||||
// TODO refactor - remove compilations
|
||||
const _sch = getCompilingSchema.call(this, sch)
|
||||
if (_sch) return _sch
|
||||
const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails
|
||||
const {es5, lines} = this.opts.code
|
||||
const {ownProperties} = this.opts
|
||||
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
|
||||
let _ValidationError
|
||||
if (sch.$async) {
|
||||
_ValidationError = gen.scopeValue("Error", {
|
||||
ref: ValidationError,
|
||||
code: _`require("ajv/dist/runtime/validation_error").default`,
|
||||
})
|
||||
}
|
||||
|
||||
const validateName = gen.scopeName("validate")
|
||||
sch.validateName = validateName
|
||||
|
||||
const schemaCxt: SchemaCxt = {
|
||||
gen,
|
||||
allErrors: this.opts.allErrors,
|
||||
data: N.data,
|
||||
parentData: N.parentData,
|
||||
parentDataProperty: N.parentDataProperty,
|
||||
dataNames: [N.data],
|
||||
dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
|
||||
dataLevel: 0,
|
||||
dataTypes: [],
|
||||
definedProperties: new Set<string>(),
|
||||
topSchemaRef: gen.scopeValue(
|
||||
"schema",
|
||||
this.opts.code.source === true
|
||||
? {ref: sch.schema, code: stringify(sch.schema)}
|
||||
: {ref: sch.schema}
|
||||
),
|
||||
validateName,
|
||||
ValidationError: _ValidationError,
|
||||
schema: sch.schema,
|
||||
schemaEnv: sch,
|
||||
rootId,
|
||||
baseId: sch.baseId || rootId,
|
||||
schemaPath: nil,
|
||||
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
|
||||
errorPath: _`""`,
|
||||
opts: this.opts,
|
||||
self: this,
|
||||
}
|
||||
|
||||
let sourceCode: string | undefined
|
||||
try {
|
||||
this._compilations.add(sch)
|
||||
validateFunctionCode(schemaCxt)
|
||||
gen.optimize(this.opts.code.optimize)
|
||||
// gen.optimize(1)
|
||||
const validateCode = gen.toString()
|
||||
sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
|
||||
// console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
|
||||
if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
|
||||
// console.log("\n\n\n *** \n", sourceCode)
|
||||
const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
|
||||
const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
|
||||
this.scope.value(validateName, {ref: validate})
|
||||
|
||||
validate.errors = null
|
||||
validate.schema = sch.schema
|
||||
validate.schemaEnv = sch
|
||||
if (sch.$async) (validate as AsyncValidateFunction).$async = true
|
||||
if (this.opts.code.source === true) {
|
||||
validate.source = {validateName, validateCode, scopeValues: gen._values}
|
||||
}
|
||||
if (this.opts.unevaluated) {
|
||||
const {props, items} = schemaCxt
|
||||
validate.evaluated = {
|
||||
props: props instanceof Name ? undefined : props,
|
||||
items: items instanceof Name ? undefined : items,
|
||||
dynamicProps: props instanceof Name,
|
||||
dynamicItems: items instanceof Name,
|
||||
}
|
||||
if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
|
||||
}
|
||||
sch.validate = validate
|
||||
return sch
|
||||
} catch (e) {
|
||||
delete sch.validate
|
||||
delete sch.validateName
|
||||
if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
|
||||
// console.log("\n\n\n *** \n", sourceCode, this.opts)
|
||||
throw e
|
||||
} finally {
|
||||
this._compilations.delete(sch)
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveRef(
|
||||
this: Ajv,
|
||||
root: SchemaEnv,
|
||||
baseId: string,
|
||||
ref: string
|
||||
): AnySchema | SchemaEnv | undefined {
|
||||
ref = resolveUrl(this.opts.uriResolver, baseId, ref)
|
||||
const schOrFunc = root.refs[ref]
|
||||
if (schOrFunc) return schOrFunc
|
||||
|
||||
let _sch = resolve.call(this, root, ref)
|
||||
if (_sch === undefined) {
|
||||
const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
|
||||
const {schemaId} = this.opts
|
||||
if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})
|
||||
}
|
||||
|
||||
if (_sch === undefined) return
|
||||
return (root.refs[ref] = inlineOrCompile.call(this, _sch))
|
||||
}
|
||||
|
||||
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
|
||||
if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
|
||||
return sch.validate ? sch : compileSchema.call(this, sch)
|
||||
}
|
||||
|
||||
// Index of schema compilation in the currently compiled list
|
||||
export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
|
||||
for (const sch of this._compilations) {
|
||||
if (sameSchemaEnv(sch, schEnv)) return sch
|
||||
}
|
||||
}
|
||||
|
||||
function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
|
||||
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
|
||||
}
|
||||
|
||||
// resolve and compile the references ($ref)
|
||||
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
|
||||
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)
|
||||
}
|
||||
|
||||
// Resolve schema, its root and baseId
|
||||
export 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)
|
||||
}
|
||||
|
||||
const PREVENT_SCOPE_CHANGE = new Set([
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"enum",
|
||||
"dependencies",
|
||||
"definitions",
|
||||
])
|
||||
|
||||
function getJsonPointer(
|
||||
this: Ajv,
|
||||
parsedRef: URIComponent,
|
||||
{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
|
||||
}
|
||||
411
electron/node_modules/ajv/lib/compile/jtd/parse.ts
generated
vendored
Normal file
411
electron/node_modules/ajv/lib/compile/jtd/parse.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
import type Ajv from "../../core"
|
||||
import type {SchemaObject} from "../../types"
|
||||
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
|
||||
import {SchemaEnv, getCompilingSchema} from ".."
|
||||
import {_, str, and, or, nil, not, CodeGen, Code, Name, SafeExpr} from "../codegen"
|
||||
import MissingRefError from "../ref_error"
|
||||
import N from "../names"
|
||||
import {hasPropFunc} from "../../vocabularies/code"
|
||||
import {hasRef} from "../../vocabularies/jtd/ref"
|
||||
import {intRange, IntType} from "../../vocabularies/jtd/type"
|
||||
import {parseJson, parseJsonNumber, parseJsonString} from "../../runtime/parseJson"
|
||||
import {useFunc} from "../util"
|
||||
import validTimestamp from "../../runtime/timestamp"
|
||||
|
||||
type GenParse = (cxt: ParseCxt) => void
|
||||
|
||||
const genParse: {[F in JTDForm]: GenParse} = {
|
||||
elements: parseElements,
|
||||
values: parseValues,
|
||||
discriminator: parseDiscriminator,
|
||||
properties: parseProperties,
|
||||
optionalProperties: parseProperties,
|
||||
enum: parseEnum,
|
||||
type: parseType,
|
||||
ref: parseRef,
|
||||
}
|
||||
|
||||
interface ParseCxt {
|
||||
readonly gen: CodeGen
|
||||
readonly self: Ajv // current Ajv instance
|
||||
readonly schemaEnv: SchemaEnv
|
||||
readonly definitions: SchemaObjectMap
|
||||
schema: SchemaObject
|
||||
data: Code
|
||||
parseName: Name
|
||||
char: Name
|
||||
}
|
||||
|
||||
export default function compileParser(
|
||||
this: Ajv,
|
||||
sch: SchemaEnv,
|
||||
definitions: SchemaObjectMap
|
||||
): SchemaEnv {
|
||||
const _sch = getCompilingSchema.call(this, sch)
|
||||
if (_sch) return _sch
|
||||
const {es5, lines} = this.opts.code
|
||||
const {ownProperties} = this.opts
|
||||
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
|
||||
const parseName = gen.scopeName("parse")
|
||||
const cxt: ParseCxt = {
|
||||
self: this,
|
||||
gen,
|
||||
schema: sch.schema as SchemaObject,
|
||||
schemaEnv: sch,
|
||||
definitions,
|
||||
data: N.data,
|
||||
parseName,
|
||||
char: gen.name("c"),
|
||||
}
|
||||
|
||||
let sourceCode: string | undefined
|
||||
try {
|
||||
this._compilations.add(sch)
|
||||
sch.parseName = parseName
|
||||
parserFunction(cxt)
|
||||
gen.optimize(this.opts.code.optimize)
|
||||
const parseFuncCode = gen.toString()
|
||||
sourceCode = `${gen.scopeRefs(N.scope)}return ${parseFuncCode}`
|
||||
const makeParse = new Function(`${N.scope}`, sourceCode)
|
||||
const parse: (json: string) => unknown = makeParse(this.scope.get())
|
||||
this.scope.value(parseName, {ref: parse})
|
||||
sch.parse = parse
|
||||
} catch (e) {
|
||||
if (sourceCode) this.logger.error("Error compiling parser, function code:", sourceCode)
|
||||
delete sch.parse
|
||||
delete sch.parseName
|
||||
throw e
|
||||
} finally {
|
||||
this._compilations.delete(sch)
|
||||
}
|
||||
return sch
|
||||
}
|
||||
|
||||
const undef = _`undefined`
|
||||
|
||||
function parserFunction(cxt: ParseCxt): void {
|
||||
const {gen, parseName, char} = cxt
|
||||
gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => {
|
||||
gen.let(N.data)
|
||||
gen.let(char)
|
||||
gen.assign(_`${parseName}.message`, undef)
|
||||
gen.assign(_`${parseName}.position`, undef)
|
||||
gen.assign(N.jsonPos, _`${N.jsonPos} || 0`)
|
||||
gen.const(N.jsonLen, _`${N.json}.length`)
|
||||
parseCode(cxt)
|
||||
skipWhitespace(cxt)
|
||||
gen.if(N.jsonPart, () => {
|
||||
gen.assign(_`${parseName}.position`, N.jsonPos)
|
||||
gen.return(N.data)
|
||||
})
|
||||
gen.if(_`${N.jsonPos} === ${N.jsonLen}`, () => gen.return(N.data))
|
||||
jsonSyntaxError(cxt)
|
||||
})
|
||||
}
|
||||
|
||||
function parseCode(cxt: ParseCxt): void {
|
||||
let form: JTDForm | undefined
|
||||
for (const key of jtdForms) {
|
||||
if (key in cxt.schema) {
|
||||
form = key
|
||||
break
|
||||
}
|
||||
}
|
||||
if (form) parseNullable(cxt, genParse[form])
|
||||
else parseEmpty(cxt)
|
||||
}
|
||||
|
||||
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError))
|
||||
|
||||
function parseNullable(cxt: ParseCxt, parseForm: GenParse): void {
|
||||
const {gen, schema, data} = cxt
|
||||
if (!schema.nullable) return parseForm(cxt)
|
||||
tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null))
|
||||
}
|
||||
|
||||
function parseElements(cxt: ParseCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
parseToken(cxt, "[")
|
||||
const ix = gen.let("i", 0)
|
||||
gen.assign(data, _`[]`)
|
||||
parseItems(cxt, "]", () => {
|
||||
const el = gen.let("el")
|
||||
parseCode({...cxt, schema: schema.elements, data: el})
|
||||
gen.assign(_`${data}[${ix}++]`, el)
|
||||
})
|
||||
}
|
||||
|
||||
function parseValues(cxt: ParseCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
parseToken(cxt, "{")
|
||||
gen.assign(data, _`{}`)
|
||||
parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values))
|
||||
}
|
||||
|
||||
function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
|
||||
tryParseItems(cxt, endToken, block)
|
||||
parseToken(cxt, endToken)
|
||||
}
|
||||
|
||||
function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void {
|
||||
const {gen} = cxt
|
||||
gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
|
||||
block()
|
||||
tryParseToken(cxt, ",", () => gen.break(), hasItem)
|
||||
})
|
||||
|
||||
function hasItem(): void {
|
||||
tryParseToken(cxt, endToken, () => {}, jsonSyntaxError)
|
||||
}
|
||||
}
|
||||
|
||||
function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void {
|
||||
const {gen} = cxt
|
||||
const key = gen.let("key")
|
||||
parseString({...cxt, data: key})
|
||||
parseToken(cxt, ":")
|
||||
parsePropertyValue(cxt, key, schema)
|
||||
}
|
||||
|
||||
function parseDiscriminator(cxt: ParseCxt): void {
|
||||
const {gen, data, schema} = cxt
|
||||
const {discriminator, mapping} = schema
|
||||
parseToken(cxt, "{")
|
||||
gen.assign(data, _`{}`)
|
||||
const startPos = gen.const("pos", N.jsonPos)
|
||||
const value = gen.let("value")
|
||||
const tag = gen.let("tag")
|
||||
tryParseItems(cxt, "}", () => {
|
||||
const key = gen.let("key")
|
||||
parseString({...cxt, data: key})
|
||||
parseToken(cxt, ":")
|
||||
gen.if(
|
||||
_`${key} === ${discriminator}`,
|
||||
() => {
|
||||
parseString({...cxt, data: tag})
|
||||
gen.assign(_`${data}[${key}]`, tag)
|
||||
gen.break()
|
||||
},
|
||||
() => parseEmpty({...cxt, data: value}) // can be discarded/skipped
|
||||
)
|
||||
})
|
||||
gen.assign(N.jsonPos, startPos)
|
||||
gen.if(_`${tag} === undefined`)
|
||||
parsingError(cxt, str`discriminator tag not found`)
|
||||
for (const tagValue in mapping) {
|
||||
gen.elseIf(_`${tag} === ${tagValue}`)
|
||||
parseSchemaProperties({...cxt, schema: mapping[tagValue]}, discriminator)
|
||||
}
|
||||
gen.else()
|
||||
parsingError(cxt, str`discriminator value not in schema`)
|
||||
gen.endIf()
|
||||
}
|
||||
|
||||
function parseProperties(cxt: ParseCxt): void {
|
||||
const {gen, data} = cxt
|
||||
parseToken(cxt, "{")
|
||||
gen.assign(data, _`{}`)
|
||||
parseSchemaProperties(cxt)
|
||||
}
|
||||
|
||||
function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void {
|
||||
const {gen, schema, data} = cxt
|
||||
const {properties, optionalProperties, additionalProperties} = schema
|
||||
parseItems(cxt, "}", () => {
|
||||
const key = gen.let("key")
|
||||
parseString({...cxt, data: key})
|
||||
parseToken(cxt, ":")
|
||||
gen.if(false)
|
||||
parseDefinedProperty(cxt, key, properties)
|
||||
parseDefinedProperty(cxt, key, optionalProperties)
|
||||
if (discriminator) {
|
||||
gen.elseIf(_`${key} === ${discriminator}`)
|
||||
const tag = gen.let("tag")
|
||||
parseString({...cxt, data: tag}) // can be discarded, it is already assigned
|
||||
}
|
||||
gen.else()
|
||||
if (additionalProperties) {
|
||||
parseEmpty({...cxt, data: _`${data}[${key}]`})
|
||||
} else {
|
||||
parsingError(cxt, str`property ${key} not allowed`)
|
||||
}
|
||||
gen.endIf()
|
||||
})
|
||||
if (properties) {
|
||||
const hasProp = hasPropFunc(gen)
|
||||
const allProps: Code = and(
|
||||
...Object.keys(properties).map((p): Code => _`${hasProp}.call(${data}, ${p})`)
|
||||
)
|
||||
gen.if(not(allProps), () => parsingError(cxt, str`missing required properties`))
|
||||
}
|
||||
}
|
||||
|
||||
function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void {
|
||||
const {gen} = cxt
|
||||
for (const prop in schemas) {
|
||||
gen.elseIf(_`${key} === ${prop}`)
|
||||
parsePropertyValue(cxt, key, schemas[prop] as SchemaObject)
|
||||
}
|
||||
}
|
||||
|
||||
function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void {
|
||||
parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`})
|
||||
}
|
||||
|
||||
function parseType(cxt: ParseCxt): void {
|
||||
const {gen, schema, data, self} = cxt
|
||||
switch (schema.type) {
|
||||
case "boolean":
|
||||
parseBoolean(cxt)
|
||||
break
|
||||
case "string":
|
||||
parseString(cxt)
|
||||
break
|
||||
case "timestamp": {
|
||||
parseString(cxt)
|
||||
const vts = useFunc(gen, validTimestamp)
|
||||
const {allowDate, parseDate} = self.opts
|
||||
const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})`
|
||||
const fail: Code = parseDate
|
||||
? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`)
|
||||
: notValid
|
||||
gen.if(fail, () => parsingError(cxt, str`invalid timestamp`))
|
||||
break
|
||||
}
|
||||
case "float32":
|
||||
case "float64":
|
||||
parseNumber(cxt)
|
||||
break
|
||||
default: {
|
||||
const t = schema.type as IntType
|
||||
if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
|
||||
parseNumber(cxt, 16) // 2 ** 53 - max safe integer
|
||||
if (t === "uint32") {
|
||||
gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`))
|
||||
}
|
||||
} else {
|
||||
const [min, max, maxDigits] = intRange[t]
|
||||
parseNumber(cxt, maxDigits)
|
||||
gen.if(_`${data} < ${min} || ${data} > ${max}`, () =>
|
||||
parsingError(cxt, str`integer out of range`)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseString(cxt: ParseCxt): void {
|
||||
parseToken(cxt, '"')
|
||||
parseWith(cxt, parseJsonString)
|
||||
}
|
||||
|
||||
function parseEnum(cxt: ParseCxt): void {
|
||||
const {gen, data, schema} = cxt
|
||||
const enumSch = schema.enum
|
||||
parseToken(cxt, '"')
|
||||
// TODO loopEnum
|
||||
gen.if(false)
|
||||
for (const value of enumSch) {
|
||||
const valueStr = JSON.stringify(value).slice(1) // remove starting quote
|
||||
gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`)
|
||||
gen.assign(data, str`${value}`)
|
||||
gen.add(N.jsonPos, valueStr.length)
|
||||
}
|
||||
gen.else()
|
||||
jsonSyntaxError(cxt)
|
||||
gen.endIf()
|
||||
}
|
||||
|
||||
function parseNumber(cxt: ParseCxt, maxDigits?: number): void {
|
||||
const {gen} = cxt
|
||||
skipWhitespace(cxt)
|
||||
gen.if(
|
||||
_`"-0123456789".indexOf(${jsonSlice(1)}) < 0`,
|
||||
() => jsonSyntaxError(cxt),
|
||||
() => parseWith(cxt, parseJsonNumber, maxDigits)
|
||||
)
|
||||
}
|
||||
|
||||
function parseBooleanToken(bool: boolean, fail: GenParse): GenParse {
|
||||
return (cxt) => {
|
||||
const {gen, data} = cxt
|
||||
tryParseToken(
|
||||
cxt,
|
||||
`${bool}`,
|
||||
() => fail(cxt),
|
||||
() => gen.assign(data, bool)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function parseRef(cxt: ParseCxt): void {
|
||||
const {gen, self, definitions, schema, schemaEnv} = cxt
|
||||
const {ref} = schema
|
||||
const refSchema = definitions[ref]
|
||||
if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
|
||||
if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema})
|
||||
const {root} = schemaEnv
|
||||
const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
|
||||
partialParse(cxt, getParser(gen, sch), true)
|
||||
}
|
||||
|
||||
function getParser(gen: CodeGen, sch: SchemaEnv): Code {
|
||||
return sch.parse
|
||||
? gen.scopeValue("parse", {ref: sch.parse})
|
||||
: _`${gen.scopeValue("wrapper", {ref: sch})}.parse`
|
||||
}
|
||||
|
||||
function parseEmpty(cxt: ParseCxt): void {
|
||||
parseWith(cxt, parseJson)
|
||||
}
|
||||
|
||||
function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void {
|
||||
partialParse(cxt, useFunc(cxt.gen, parseFunc), args)
|
||||
}
|
||||
|
||||
function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void {
|
||||
const {gen, data} = cxt
|
||||
gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`)
|
||||
gen.assign(N.jsonPos, _`${parseFunc}.position`)
|
||||
gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`))
|
||||
}
|
||||
|
||||
function parseToken(cxt: ParseCxt, tok: string): void {
|
||||
tryParseToken(cxt, tok, jsonSyntaxError)
|
||||
}
|
||||
|
||||
function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void {
|
||||
const {gen} = cxt
|
||||
const n = tok.length
|
||||
skipWhitespace(cxt)
|
||||
gen.if(
|
||||
_`${jsonSlice(n)} === ${tok}`,
|
||||
() => {
|
||||
gen.add(N.jsonPos, n)
|
||||
success?.(cxt)
|
||||
},
|
||||
() => fail(cxt)
|
||||
)
|
||||
}
|
||||
|
||||
function skipWhitespace({gen, char: c}: ParseCxt): void {
|
||||
gen.code(
|
||||
_`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;`
|
||||
)
|
||||
}
|
||||
|
||||
function jsonSlice(len: number | Name): Code {
|
||||
return len === 1
|
||||
? _`${N.json}[${N.jsonPos}]`
|
||||
: _`${N.json}.slice(${N.jsonPos}, ${N.jsonPos}+${len})`
|
||||
}
|
||||
|
||||
function jsonSyntaxError(cxt: ParseCxt): void {
|
||||
parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`)
|
||||
}
|
||||
|
||||
function parsingError({gen, parseName}: ParseCxt, msg: Code): void {
|
||||
gen.assign(_`${parseName}.message`, msg)
|
||||
gen.assign(_`${parseName}.position`, N.jsonPos)
|
||||
gen.return(undef)
|
||||
}
|
||||
277
electron/node_modules/ajv/lib/compile/jtd/serialize.ts
generated
vendored
Normal file
277
electron/node_modules/ajv/lib/compile/jtd/serialize.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
import type Ajv from "../../core"
|
||||
import type {SchemaObject} from "../../types"
|
||||
import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
|
||||
import {SchemaEnv, getCompilingSchema} from ".."
|
||||
import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen"
|
||||
import MissingRefError from "../ref_error"
|
||||
import N from "../names"
|
||||
import {isOwnProperty} from "../../vocabularies/code"
|
||||
import {hasRef} from "../../vocabularies/jtd/ref"
|
||||
import {useFunc} from "../util"
|
||||
import quote from "../../runtime/quote"
|
||||
|
||||
const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = {
|
||||
elements: serializeElements,
|
||||
values: serializeValues,
|
||||
discriminator: serializeDiscriminator,
|
||||
properties: serializeProperties,
|
||||
optionalProperties: serializeProperties,
|
||||
enum: serializeString,
|
||||
type: serializeType,
|
||||
ref: serializeRef,
|
||||
}
|
||||
|
||||
interface SerializeCxt {
|
||||
readonly gen: CodeGen
|
||||
readonly self: Ajv // current Ajv instance
|
||||
readonly schemaEnv: SchemaEnv
|
||||
readonly definitions: SchemaObjectMap
|
||||
schema: SchemaObject
|
||||
data: Code
|
||||
}
|
||||
|
||||
export default function compileSerializer(
|
||||
this: Ajv,
|
||||
sch: SchemaEnv,
|
||||
definitions: SchemaObjectMap
|
||||
): SchemaEnv {
|
||||
const _sch = getCompilingSchema.call(this, sch)
|
||||
if (_sch) return _sch
|
||||
const {es5, lines} = this.opts.code
|
||||
const {ownProperties} = this.opts
|
||||
const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
|
||||
const serializeName = gen.scopeName("serialize")
|
||||
const cxt: SerializeCxt = {
|
||||
self: this,
|
||||
gen,
|
||||
schema: sch.schema as SchemaObject,
|
||||
schemaEnv: sch,
|
||||
definitions,
|
||||
data: N.data,
|
||||
}
|
||||
|
||||
let sourceCode: string | undefined
|
||||
try {
|
||||
this._compilations.add(sch)
|
||||
sch.serializeName = serializeName
|
||||
gen.func(serializeName, N.data, false, () => {
|
||||
gen.let(N.json, str``)
|
||||
serializeCode(cxt)
|
||||
gen.return(N.json)
|
||||
})
|
||||
gen.optimize(this.opts.code.optimize)
|
||||
const serializeFuncCode = gen.toString()
|
||||
sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}`
|
||||
const makeSerialize = new Function(`${N.scope}`, sourceCode)
|
||||
const serialize: (data: unknown) => string = makeSerialize(this.scope.get())
|
||||
this.scope.value(serializeName, {ref: serialize})
|
||||
sch.serialize = serialize
|
||||
} catch (e) {
|
||||
if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode)
|
||||
delete sch.serialize
|
||||
delete sch.serializeName
|
||||
throw e
|
||||
} finally {
|
||||
this._compilations.delete(sch)
|
||||
}
|
||||
return sch
|
||||
}
|
||||
|
||||
function serializeCode(cxt: SerializeCxt): void {
|
||||
let form: JTDForm | undefined
|
||||
for (const key of jtdForms) {
|
||||
if (key in cxt.schema) {
|
||||
form = key
|
||||
break
|
||||
}
|
||||
}
|
||||
serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty)
|
||||
}
|
||||
|
||||
function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void {
|
||||
const {gen, schema, data} = cxt
|
||||
if (!schema.nullable) return serializeForm(cxt)
|
||||
gen.if(
|
||||
_`${data} === undefined || ${data} === null`,
|
||||
() => gen.add(N.json, _`"null"`),
|
||||
() => serializeForm(cxt)
|
||||
)
|
||||
}
|
||||
|
||||
function serializeElements(cxt: SerializeCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
gen.add(N.json, str`[`)
|
||||
const first = gen.let("first", true)
|
||||
gen.forOf("el", data, (el) => {
|
||||
addComma(cxt, first)
|
||||
serializeCode({...cxt, schema: schema.elements, data: el})
|
||||
})
|
||||
gen.add(N.json, str`]`)
|
||||
}
|
||||
|
||||
function serializeValues(cxt: SerializeCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
gen.add(N.json, str`{`)
|
||||
const first = gen.let("first", true)
|
||||
gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first))
|
||||
gen.add(N.json, str`}`)
|
||||
}
|
||||
|
||||
function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void {
|
||||
const {gen, data} = cxt
|
||||
addComma(cxt, first)
|
||||
serializeString({...cxt, data: key})
|
||||
gen.add(N.json, str`:`)
|
||||
const value = gen.const("value", _`${data}${getProperty(key)}`)
|
||||
serializeCode({...cxt, schema, data: value})
|
||||
}
|
||||
|
||||
function serializeDiscriminator(cxt: SerializeCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
const {discriminator} = schema
|
||||
gen.add(N.json, str`{${JSON.stringify(discriminator)}:`)
|
||||
const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`)
|
||||
serializeString({...cxt, data: tag})
|
||||
gen.if(false)
|
||||
for (const tagValue in schema.mapping) {
|
||||
gen.elseIf(_`${tag} === ${tagValue}`)
|
||||
const sch = schema.mapping[tagValue]
|
||||
serializeSchemaProperties({...cxt, schema: sch}, discriminator)
|
||||
}
|
||||
gen.endIf()
|
||||
gen.add(N.json, str`}`)
|
||||
}
|
||||
|
||||
function serializeProperties(cxt: SerializeCxt): void {
|
||||
const {gen} = cxt
|
||||
gen.add(N.json, str`{`)
|
||||
serializeSchemaProperties(cxt)
|
||||
gen.add(N.json, str`}`)
|
||||
}
|
||||
|
||||
function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void {
|
||||
const {gen, schema, data} = cxt
|
||||
const {properties, optionalProperties} = schema
|
||||
const props = keys(properties)
|
||||
const optProps = keys(optionalProperties)
|
||||
const allProps = allProperties(props.concat(optProps))
|
||||
let first = !discriminator
|
||||
let firstProp: Name | undefined
|
||||
|
||||
for (const key of props) {
|
||||
if (first) first = false
|
||||
else gen.add(N.json, str`,`)
|
||||
serializeProperty(key, properties[key], keyValue(key))
|
||||
}
|
||||
if (first) firstProp = gen.let("first", true)
|
||||
for (const key of optProps) {
|
||||
const value = keyValue(key)
|
||||
gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => {
|
||||
addComma(cxt, firstProp)
|
||||
serializeProperty(key, optionalProperties[key], value)
|
||||
})
|
||||
}
|
||||
if (schema.additionalProperties) {
|
||||
gen.forIn("key", data, (key) =>
|
||||
gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp))
|
||||
)
|
||||
}
|
||||
|
||||
function keys(ps?: SchemaObjectMap): string[] {
|
||||
return ps ? Object.keys(ps) : []
|
||||
}
|
||||
|
||||
function allProperties(ps: string[]): string[] {
|
||||
if (discriminator) ps.push(discriminator)
|
||||
if (new Set(ps).size !== ps.length) {
|
||||
throw new Error("JTD: properties/optionalProperties/disciminator overlap")
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
function keyValue(key: string): Name {
|
||||
return gen.const("value", _`${data}${getProperty(key)}`)
|
||||
}
|
||||
|
||||
function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void {
|
||||
gen.add(N.json, str`${JSON.stringify(key)}:`)
|
||||
serializeCode({...cxt, schema: propSchema, data: value})
|
||||
}
|
||||
|
||||
function isAdditional(key: Name, ps: string[]): Code | true {
|
||||
return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true
|
||||
}
|
||||
}
|
||||
|
||||
function serializeType(cxt: SerializeCxt): void {
|
||||
const {gen, schema, data} = cxt
|
||||
switch (schema.type) {
|
||||
case "boolean":
|
||||
gen.add(N.json, _`${data} ? "true" : "false"`)
|
||||
break
|
||||
case "string":
|
||||
serializeString(cxt)
|
||||
break
|
||||
case "timestamp":
|
||||
gen.if(
|
||||
_`${data} instanceof Date`,
|
||||
() => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
|
||||
() => serializeString(cxt)
|
||||
)
|
||||
break
|
||||
default:
|
||||
serializeNumber(cxt)
|
||||
}
|
||||
}
|
||||
|
||||
function serializeString({gen, data}: SerializeCxt): void {
|
||||
gen.add(N.json, _`${useFunc(gen, quote)}(${data})`)
|
||||
}
|
||||
|
||||
function serializeNumber({gen, data, self}: SerializeCxt): void {
|
||||
const condition = _`${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`
|
||||
|
||||
if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
|
||||
gen.add(N.json, _`"" + ${data}`)
|
||||
} else {
|
||||
// specialNumbers === "null"
|
||||
gen.if(
|
||||
condition,
|
||||
() => gen.add(N.json, _`null`),
|
||||
() => gen.add(N.json, _`"" + ${data}`)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function serializeRef(cxt: SerializeCxt): void {
|
||||
const {gen, self, data, definitions, schema, schemaEnv} = cxt
|
||||
const {ref} = schema
|
||||
const refSchema = definitions[ref]
|
||||
if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`)
|
||||
if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema})
|
||||
const {root} = schemaEnv
|
||||
const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
|
||||
gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`)
|
||||
}
|
||||
|
||||
function getSerialize(gen: CodeGen, sch: SchemaEnv): Code {
|
||||
return sch.serialize
|
||||
? gen.scopeValue("serialize", {ref: sch.serialize})
|
||||
: _`${gen.scopeValue("wrapper", {ref: sch})}.serialize`
|
||||
}
|
||||
|
||||
function serializeEmpty({gen, data}: SerializeCxt): void {
|
||||
gen.add(N.json, _`JSON.stringify(${data})`)
|
||||
}
|
||||
|
||||
function addComma({gen}: SerializeCxt, first?: Name): void {
|
||||
if (first) {
|
||||
gen.if(
|
||||
first,
|
||||
() => gen.assign(first, false),
|
||||
() => gen.add(N.json, str`,`)
|
||||
)
|
||||
} else {
|
||||
gen.add(N.json, str`,`)
|
||||
}
|
||||
}
|
||||
16
electron/node_modules/ajv/lib/compile/jtd/types.ts
generated
vendored
Normal file
16
electron/node_modules/ajv/lib/compile/jtd/types.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import type {SchemaObject} from "../../types"
|
||||
|
||||
export type SchemaObjectMap = {[Ref in string]?: SchemaObject}
|
||||
|
||||
export const jtdForms = [
|
||||
"elements",
|
||||
"values",
|
||||
"discriminator",
|
||||
"properties",
|
||||
"optionalProperties",
|
||||
"enum",
|
||||
"type",
|
||||
"ref",
|
||||
] as const
|
||||
|
||||
export type JTDForm = (typeof jtdForms)[number]
|
||||
27
electron/node_modules/ajv/lib/compile/names.ts
generated
vendored
Normal file
27
electron/node_modules/ajv/lib/compile/names.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import {Name} from "./codegen"
|
||||
|
||||
const names = {
|
||||
// validation function arguments
|
||||
data: new Name("data"), // data passed to validation function
|
||||
// args passed from referencing schema
|
||||
valCxt: new Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
|
||||
instancePath: new Name("instancePath"),
|
||||
parentData: new Name("parentData"),
|
||||
parentDataProperty: new Name("parentDataProperty"),
|
||||
rootData: new Name("rootData"), // root data - same as the data passed to the first/top validation function
|
||||
dynamicAnchors: new Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
|
||||
// function scoped variables
|
||||
vErrors: new Name("vErrors"), // null or array of validation errors
|
||||
errors: new Name("errors"), // counter of validation errors
|
||||
this: new Name("this"),
|
||||
// "globals"
|
||||
self: new Name("self"),
|
||||
scope: new Name("scope"),
|
||||
// JTD serialize/parse name for JSON string and position
|
||||
json: new Name("json"),
|
||||
jsonPos: new Name("jsonPos"),
|
||||
jsonLen: new Name("jsonLen"),
|
||||
jsonPart: new Name("jsonPart"),
|
||||
}
|
||||
|
||||
export default names
|
||||
13
electron/node_modules/ajv/lib/compile/ref_error.ts
generated
vendored
Normal file
13
electron/node_modules/ajv/lib/compile/ref_error.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import {resolveUrl, normalizeId, getFullPath} from "./resolve"
|
||||
import type {UriResolver} from "../types"
|
||||
|
||||
export default class MissingRefError extends Error {
|
||||
readonly missingRef: string
|
||||
readonly missingSchema: string
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
270
electron/node_modules/ajv/lib/compile/resolve.js
generated
vendored
270
electron/node_modules/ajv/lib/compile/resolve.js
generated
vendored
|
|
@ -1,270 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var URI = require('uri-js')
|
||||
, equal = require('fast-deep-equal')
|
||||
, util = require('./util')
|
||||
, SchemaObject = require('./schema_obj')
|
||||
, traverse = require('json-schema-traverse');
|
||||
|
||||
module.exports = resolve;
|
||||
|
||||
resolve.normalizeId = normalizeId;
|
||||
resolve.fullPath = getFullPath;
|
||||
resolve.url = resolveUrl;
|
||||
resolve.ids = resolveIds;
|
||||
resolve.inlineRef = inlineRef;
|
||||
resolve.schema = resolveSchema;
|
||||
|
||||
/**
|
||||
* [resolve and compile the references ($ref)]
|
||||
* @this Ajv
|
||||
* @param {Function} compile reference to schema compilation funciton (localCompile)
|
||||
* @param {Object} root object with information about the root schema for the current schema
|
||||
* @param {String} ref reference to resolve
|
||||
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
|
||||
*/
|
||||
function resolve(compile, root, ref) {
|
||||
/* jshint validthis: true */
|
||||
var refVal = this._refs[ref];
|
||||
if (typeof refVal == 'string') {
|
||||
if (this._refs[refVal]) refVal = this._refs[refVal];
|
||||
else return resolve.call(this, compile, root, refVal);
|
||||
}
|
||||
|
||||
refVal = refVal || this._schemas[ref];
|
||||
if (refVal instanceof SchemaObject) {
|
||||
return inlineRef(refVal.schema, this._opts.inlineRefs)
|
||||
? refVal.schema
|
||||
: refVal.validate || this._compile(refVal);
|
||||
}
|
||||
|
||||
var res = resolveSchema.call(this, root, ref);
|
||||
var schema, v, baseId;
|
||||
if (res) {
|
||||
schema = res.schema;
|
||||
root = res.root;
|
||||
baseId = res.baseId;
|
||||
}
|
||||
|
||||
if (schema instanceof SchemaObject) {
|
||||
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
|
||||
} else if (schema !== undefined) {
|
||||
v = inlineRef(schema, this._opts.inlineRefs)
|
||||
? schema
|
||||
: compile.call(this, schema, root, undefined, baseId);
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Resolve schema, its root and baseId
|
||||
* @this Ajv
|
||||
* @param {Object} root root object with properties schema, refVal, refs
|
||||
* @param {String} ref reference to resolve
|
||||
* @return {Object} object with properties schema, root, baseId
|
||||
*/
|
||||
function resolveSchema(root, ref) {
|
||||
/* jshint validthis: true */
|
||||
var p = URI.parse(ref)
|
||||
, refPath = _getFullPath(p)
|
||||
, baseId = getFullPath(this._getId(root.schema));
|
||||
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
|
||||
var id = normalizeId(refPath);
|
||||
var refVal = this._refs[id];
|
||||
if (typeof refVal == 'string') {
|
||||
return resolveRecursive.call(this, root, refVal, p);
|
||||
} else if (refVal instanceof SchemaObject) {
|
||||
if (!refVal.validate) this._compile(refVal);
|
||||
root = refVal;
|
||||
} else {
|
||||
refVal = this._schemas[id];
|
||||
if (refVal instanceof SchemaObject) {
|
||||
if (!refVal.validate) this._compile(refVal);
|
||||
if (id == normalizeId(ref))
|
||||
return { schema: refVal, root: root, baseId: baseId };
|
||||
root = refVal;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!root.schema) return;
|
||||
baseId = getFullPath(this._getId(root.schema));
|
||||
}
|
||||
return getJsonPointer.call(this, p, baseId, root.schema, root);
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function resolveRecursive(root, ref, parsedRef) {
|
||||
/* jshint validthis: true */
|
||||
var res = resolveSchema.call(this, root, ref);
|
||||
if (res) {
|
||||
var schema = res.schema;
|
||||
var baseId = res.baseId;
|
||||
root = res.root;
|
||||
var id = this._getId(schema);
|
||||
if (id) baseId = resolveUrl(baseId, id);
|
||||
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
|
||||
/* @this Ajv */
|
||||
function getJsonPointer(parsedRef, baseId, schema, root) {
|
||||
/* jshint validthis: true */
|
||||
parsedRef.fragment = parsedRef.fragment || '';
|
||||
if (parsedRef.fragment.slice(0,1) != '/') return;
|
||||
var parts = parsedRef.fragment.split('/');
|
||||
|
||||
for (var i = 1; i < parts.length; i++) {
|
||||
var part = parts[i];
|
||||
if (part) {
|
||||
part = util.unescapeFragment(part);
|
||||
schema = schema[part];
|
||||
if (schema === undefined) break;
|
||||
var id;
|
||||
if (!PREVENT_SCOPE_CHANGE[part]) {
|
||||
id = this._getId(schema);
|
||||
if (id) baseId = resolveUrl(baseId, id);
|
||||
if (schema.$ref) {
|
||||
var $ref = resolveUrl(baseId, schema.$ref);
|
||||
var res = resolveSchema.call(this, root, $ref);
|
||||
if (res) {
|
||||
schema = res.schema;
|
||||
root = res.root;
|
||||
baseId = res.baseId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (schema !== undefined && schema !== root.schema)
|
||||
return { schema: schema, root: root, baseId: baseId };
|
||||
}
|
||||
|
||||
|
||||
var SIMPLE_INLINED = util.toHash([
|
||||
'type', 'format', 'pattern',
|
||||
'maxLength', 'minLength',
|
||||
'maxProperties', 'minProperties',
|
||||
'maxItems', 'minItems',
|
||||
'maximum', 'minimum',
|
||||
'uniqueItems', 'multipleOf',
|
||||
'required', 'enum'
|
||||
]);
|
||||
function inlineRef(schema, limit) {
|
||||
if (limit === false) return false;
|
||||
if (limit === undefined || limit === true) return checkNoRef(schema);
|
||||
else if (limit) return countKeys(schema) <= limit;
|
||||
}
|
||||
|
||||
|
||||
function checkNoRef(schema) {
|
||||
var item;
|
||||
if (Array.isArray(schema)) {
|
||||
for (var i=0; i<schema.length; i++) {
|
||||
item = schema[i];
|
||||
if (typeof item == 'object' && !checkNoRef(item)) return false;
|
||||
}
|
||||
} else {
|
||||
for (var key in schema) {
|
||||
if (key == '$ref') return false;
|
||||
item = schema[key];
|
||||
if (typeof item == 'object' && !checkNoRef(item)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
function countKeys(schema) {
|
||||
var count = 0, item;
|
||||
if (Array.isArray(schema)) {
|
||||
for (var i=0; i<schema.length; i++) {
|
||||
item = schema[i];
|
||||
if (typeof item == 'object') count += countKeys(item);
|
||||
if (count == Infinity) return Infinity;
|
||||
}
|
||||
} else {
|
||||
for (var key in schema) {
|
||||
if (key == '$ref') return Infinity;
|
||||
if (SIMPLE_INLINED[key]) {
|
||||
count++;
|
||||
} else {
|
||||
item = schema[key];
|
||||
if (typeof item == 'object') count += countKeys(item) + 1;
|
||||
if (count == Infinity) return Infinity;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
function getFullPath(id, normalize) {
|
||||
if (normalize !== false) id = normalizeId(id);
|
||||
var p = URI.parse(id);
|
||||
return _getFullPath(p);
|
||||
}
|
||||
|
||||
|
||||
function _getFullPath(p) {
|
||||
return URI.serialize(p).split('#')[0] + '#';
|
||||
}
|
||||
|
||||
|
||||
var TRAILING_SLASH_HASH = /#\/?$/;
|
||||
function normalizeId(id) {
|
||||
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
|
||||
}
|
||||
|
||||
|
||||
function resolveUrl(baseId, id) {
|
||||
id = normalizeId(id);
|
||||
return URI.resolve(baseId, id);
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function resolveIds(schema) {
|
||||
var schemaId = normalizeId(this._getId(schema));
|
||||
var baseIds = {'': schemaId};
|
||||
var fullPaths = {'': getFullPath(schemaId, false)};
|
||||
var localRefs = {};
|
||||
var self = this;
|
||||
|
||||
traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
||||
if (jsonPtr === '') return;
|
||||
var id = self._getId(sch);
|
||||
var baseId = baseIds[parentJsonPtr];
|
||||
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
|
||||
if (keyIndex !== undefined)
|
||||
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
|
||||
|
||||
if (typeof id == 'string') {
|
||||
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
|
||||
|
||||
var refVal = self._refs[id];
|
||||
if (typeof refVal == 'string') refVal = self._refs[refVal];
|
||||
if (refVal && refVal.schema) {
|
||||
if (!equal(sch, refVal.schema))
|
||||
throw new Error('id "' + id + '" resolves to more than one 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');
|
||||
localRefs[id] = sch;
|
||||
} else {
|
||||
self._refs[id] = fullPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
baseIds[jsonPtr] = baseId;
|
||||
fullPaths[jsonPtr] = fullPath;
|
||||
});
|
||||
|
||||
return localRefs;
|
||||
}
|
||||
149
electron/node_modules/ajv/lib/compile/resolve.ts
generated
vendored
Normal file
149
electron/node_modules/ajv/lib/compile/resolve.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import type {AnySchema, AnySchemaObject, UriResolver} from "../types"
|
||||
import type Ajv from "../ajv"
|
||||
import type {URIComponent} from "fast-uri"
|
||||
import {eachItem} from "./util"
|
||||
import * as equal from "fast-deep-equal"
|
||||
import * as traverse from "json-schema-traverse"
|
||||
|
||||
// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution
|
||||
export type LocalRefs = {[Ref in string]?: AnySchemaObject}
|
||||
|
||||
// TODO refactor to use keyword definitions
|
||||
const SIMPLE_INLINED = new Set([
|
||||
"type",
|
||||
"format",
|
||||
"pattern",
|
||||
"maxLength",
|
||||
"minLength",
|
||||
"maxProperties",
|
||||
"minProperties",
|
||||
"maxItems",
|
||||
"minItems",
|
||||
"maximum",
|
||||
"minimum",
|
||||
"uniqueItems",
|
||||
"multipleOf",
|
||||
"required",
|
||||
"enum",
|
||||
"const",
|
||||
])
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
const REF_KEYWORDS = new Set([
|
||||
"$ref",
|
||||
"$recursiveRef",
|
||||
"$recursiveAnchor",
|
||||
"$dynamicRef",
|
||||
"$dynamicAnchor",
|
||||
])
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
export function getFullPath(resolver: UriResolver, id = "", normalize?: boolean): string {
|
||||
if (normalize !== false) id = normalizeId(id)
|
||||
const p = resolver.parse(id)
|
||||
return _getFullPath(resolver, p)
|
||||
}
|
||||
|
||||
export function _getFullPath(resolver: UriResolver, p: URIComponent): string {
|
||||
const serialized = resolver.serialize(p)
|
||||
return serialized.split("#")[0] + "#"
|
||||
}
|
||||
|
||||
const TRAILING_SLASH_HASH = /#\/?$/
|
||||
export function normalizeId(id: string | undefined): string {
|
||||
return id ? id.replace(TRAILING_SLASH_HASH, "") : ""
|
||||
}
|
||||
|
||||
export function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {
|
||||
id = normalizeId(id)
|
||||
return resolver.resolve(baseId, id)
|
||||
}
|
||||
|
||||
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i
|
||||
|
||||
export 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 innerBaseId = baseIds[parentJsonPtr]
|
||||
if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId])
|
||||
addAnchor.call(this, sch.$anchor)
|
||||
addAnchor.call(this, sch.$dynamicAnchor)
|
||||
baseIds[jsonPtr] = innerBaseId
|
||||
|
||||
function addRef(this: Ajv, ref: string): string {
|
||||
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||
const _resolve = this.opts.uriResolver.resolve
|
||||
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, 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`)
|
||||
}
|
||||
}
|
||||
66
electron/node_modules/ajv/lib/compile/rules.js
generated
vendored
66
electron/node_modules/ajv/lib/compile/rules.js
generated
vendored
|
|
@ -1,66 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var ruleModules = require('../dotjs')
|
||||
, toHash = require('./util').toHash;
|
||||
|
||||
module.exports = function rules() {
|
||||
var RULES = [
|
||||
{ type: 'number',
|
||||
rules: [ { 'maximum': ['exclusiveMaximum'] },
|
||||
{ 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
|
||||
{ type: 'string',
|
||||
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
|
||||
{ type: 'array',
|
||||
rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
|
||||
{ type: 'object',
|
||||
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
|
||||
{ 'properties': ['additionalProperties', 'patternProperties'] } ] },
|
||||
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
|
||||
];
|
||||
|
||||
var ALL = [ 'type', '$comment' ];
|
||||
var KEYWORDS = [
|
||||
'$schema', '$id', 'id', '$data', '$async', 'title',
|
||||
'description', 'default', 'definitions',
|
||||
'examples', 'readOnly', 'writeOnly',
|
||||
'contentMediaType', 'contentEncoding',
|
||||
'additionalItems', 'then', 'else'
|
||||
];
|
||||
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
|
||||
RULES.all = toHash(ALL);
|
||||
RULES.types = toHash(TYPES);
|
||||
|
||||
RULES.forEach(function (group) {
|
||||
group.rules = group.rules.map(function (keyword) {
|
||||
var implKeywords;
|
||||
if (typeof keyword == 'object') {
|
||||
var key = Object.keys(keyword)[0];
|
||||
implKeywords = keyword[key];
|
||||
keyword = key;
|
||||
implKeywords.forEach(function (k) {
|
||||
ALL.push(k);
|
||||
RULES.all[k] = true;
|
||||
});
|
||||
}
|
||||
ALL.push(keyword);
|
||||
var rule = RULES.all[keyword] = {
|
||||
keyword: keyword,
|
||||
code: ruleModules[keyword],
|
||||
implements: implKeywords
|
||||
};
|
||||
return rule;
|
||||
});
|
||||
|
||||
RULES.all.$comment = {
|
||||
keyword: '$comment',
|
||||
code: ruleModules.$comment
|
||||
};
|
||||
|
||||
if (group.type) RULES.types[group.type] = group;
|
||||
});
|
||||
|
||||
RULES.keywords = toHash(ALL.concat(KEYWORDS));
|
||||
RULES.custom = {};
|
||||
|
||||
return RULES;
|
||||
};
|
||||
50
electron/node_modules/ajv/lib/compile/rules.ts
generated
vendored
Normal file
50
electron/node_modules/ajv/lib/compile/rules.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import type {AddedKeywordDefinition} from "../types"
|
||||
|
||||
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const
|
||||
|
||||
export type JSONType = (typeof _jsonTypes)[number]
|
||||
|
||||
const jsonTypes: Set<string> = new Set(_jsonTypes)
|
||||
|
||||
export function isJSONType(x: unknown): x is JSONType {
|
||||
return typeof x == "string" && jsonTypes.has(x)
|
||||
}
|
||||
|
||||
type ValidationTypes = {
|
||||
[K in JSONType]: boolean | RuleGroup | undefined
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export interface RuleGroup {
|
||||
type?: JSONType
|
||||
rules: Rule[]
|
||||
}
|
||||
|
||||
// This interface wraps KeywordDefinition because definition can have multiple keywords
|
||||
export interface Rule {
|
||||
keyword: string
|
||||
definition: AddedKeywordDefinition
|
||||
}
|
||||
|
||||
export function getRules(): ValidationRules {
|
||||
const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = {
|
||||
number: {type: "number", rules: []},
|
||||
string: {type: "string", rules: []},
|
||||
array: {type: "array", rules: []},
|
||||
object: {type: "object", rules: []},
|
||||
}
|
||||
return {
|
||||
types: {...groups, integer: true, boolean: true, null: true},
|
||||
rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],
|
||||
post: {rules: []},
|
||||
all: {},
|
||||
keywords: {},
|
||||
}
|
||||
}
|
||||
9
electron/node_modules/ajv/lib/compile/schema_obj.js
generated
vendored
9
electron/node_modules/ajv/lib/compile/schema_obj.js
generated
vendored
|
|
@ -1,9 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
module.exports = SchemaObject;
|
||||
|
||||
function SchemaObject(obj) {
|
||||
util.copy(obj, this);
|
||||
}
|
||||
20
electron/node_modules/ajv/lib/compile/ucs2length.js
generated
vendored
20
electron/node_modules/ajv/lib/compile/ucs2length.js
generated
vendored
|
|
@ -1,20 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
// https://mathiasbynens.be/notes/javascript-encoding
|
||||
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
|
||||
module.exports = function ucs2length(str) {
|
||||
var length = 0
|
||||
, len = str.length
|
||||
, pos = 0
|
||||
, value;
|
||||
while (pos < len) {
|
||||
length++;
|
||||
value = str.charCodeAt(pos++);
|
||||
if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
|
||||
// high surrogate, and there is a next character
|
||||
value = str.charCodeAt(pos);
|
||||
if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
|
||||
}
|
||||
}
|
||||
return length;
|
||||
};
|
||||
239
electron/node_modules/ajv/lib/compile/util.js
generated
vendored
239
electron/node_modules/ajv/lib/compile/util.js
generated
vendored
|
|
@ -1,239 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
|
||||
module.exports = {
|
||||
copy: copy,
|
||||
checkDataType: checkDataType,
|
||||
checkDataTypes: checkDataTypes,
|
||||
coerceToTypes: coerceToTypes,
|
||||
toHash: toHash,
|
||||
getProperty: getProperty,
|
||||
escapeQuotes: escapeQuotes,
|
||||
equal: require('fast-deep-equal'),
|
||||
ucs2length: require('./ucs2length'),
|
||||
varOccurences: varOccurences,
|
||||
varReplace: varReplace,
|
||||
schemaHasRules: schemaHasRules,
|
||||
schemaHasRulesExcept: schemaHasRulesExcept,
|
||||
schemaUnknownRules: schemaUnknownRules,
|
||||
toQuotedString: toQuotedString,
|
||||
getPathExpr: getPathExpr,
|
||||
getPath: getPath,
|
||||
getData: getData,
|
||||
unescapeFragment: unescapeFragment,
|
||||
unescapeJsonPointer: unescapeJsonPointer,
|
||||
escapeFragment: escapeFragment,
|
||||
escapeJsonPointer: escapeJsonPointer
|
||||
};
|
||||
|
||||
|
||||
function copy(o, to) {
|
||||
to = to || {};
|
||||
for (var key in o) to[key] = o[key];
|
||||
return to;
|
||||
}
|
||||
|
||||
|
||||
function checkDataType(dataType, data, strictNumbers, negate) {
|
||||
var EQUAL = negate ? ' !== ' : ' === '
|
||||
, AND = negate ? ' || ' : ' && '
|
||||
, OK = negate ? '!' : ''
|
||||
, NOT = negate ? '' : '!';
|
||||
switch (dataType) {
|
||||
case 'null': return data + EQUAL + 'null';
|
||||
case 'array': return OK + 'Array.isArray(' + data + ')';
|
||||
case 'object': return '(' + OK + data + AND +
|
||||
'typeof ' + data + EQUAL + '"object"' + AND +
|
||||
NOT + 'Array.isArray(' + data + '))';
|
||||
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
|
||||
NOT + '(' + data + ' % 1)' +
|
||||
AND + data + EQUAL + data +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkDataTypes(dataTypes, data, strictNumbers) {
|
||||
switch (dataTypes.length) {
|
||||
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
|
||||
default:
|
||||
var code = '';
|
||||
var types = toHash(dataTypes);
|
||||
if (types.array && types.object) {
|
||||
code = types.null ? '(': '(!' + data + ' || ';
|
||||
code += 'typeof ' + data + ' !== "object")';
|
||||
delete types.null;
|
||||
delete types.array;
|
||||
delete types.object;
|
||||
}
|
||||
if (types.number) delete types.integer;
|
||||
for (var t in types)
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
|
||||
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
|
||||
function coerceToTypes(optionCoerceTypes, dataTypes) {
|
||||
if (Array.isArray(dataTypes)) {
|
||||
var types = [];
|
||||
for (var i=0; i<dataTypes.length; i++) {
|
||||
var t = dataTypes[i];
|
||||
if (COERCE_TO_TYPES[t]) types[types.length] = t;
|
||||
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
|
||||
}
|
||||
if (types.length) return types;
|
||||
} else if (COERCE_TO_TYPES[dataTypes]) {
|
||||
return [dataTypes];
|
||||
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
|
||||
return ['array'];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function toHash(arr) {
|
||||
var hash = {};
|
||||
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
|
||||
return hash;
|
||||
}
|
||||
|
||||
|
||||
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
||||
var SINGLE_QUOTE = /'|\\/g;
|
||||
function getProperty(key) {
|
||||
return typeof key == 'number'
|
||||
? '[' + key + ']'
|
||||
: IDENTIFIER.test(key)
|
||||
? '.' + key
|
||||
: "['" + escapeQuotes(key) + "']";
|
||||
}
|
||||
|
||||
|
||||
function escapeQuotes(str) {
|
||||
return str.replace(SINGLE_QUOTE, '\\$&')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\f/g, '\\f')
|
||||
.replace(/\t/g, '\\t');
|
||||
}
|
||||
|
||||
|
||||
function varOccurences(str, dataVar) {
|
||||
dataVar += '[^0-9]';
|
||||
var matches = str.match(new RegExp(dataVar, 'g'));
|
||||
return matches ? matches.length : 0;
|
||||
}
|
||||
|
||||
|
||||
function varReplace(str, dataVar, expr) {
|
||||
dataVar += '([^0-9])';
|
||||
expr = expr.replace(/\$/g, '$$$$');
|
||||
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return !schema;
|
||||
for (var key in schema) if (rules[key]) return true;
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
|
||||
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
|
||||
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
|
||||
}
|
||||
|
||||
|
||||
function schemaUnknownRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return;
|
||||
for (var key in schema) if (!rules[key]) return key;
|
||||
}
|
||||
|
||||
|
||||
function toQuotedString(str) {
|
||||
return '\'' + escapeQuotes(str) + '\'';
|
||||
}
|
||||
|
||||
|
||||
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
|
||||
var path = jsonPointers // false by default
|
||||
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
|
||||
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
|
||||
return joinPaths(currentPath, path);
|
||||
}
|
||||
|
||||
|
||||
function getPath(currentPath, prop, jsonPointers) {
|
||||
var path = jsonPointers // false by default
|
||||
? toQuotedString('/' + escapeJsonPointer(prop))
|
||||
: toQuotedString(getProperty(prop));
|
||||
return joinPaths(currentPath, path);
|
||||
}
|
||||
|
||||
|
||||
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
|
||||
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
|
||||
function getData($data, lvl, paths) {
|
||||
var up, jsonPointer, data, matches;
|
||||
if ($data === '') return 'rootData';
|
||||
if ($data[0] == '/') {
|
||||
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
|
||||
jsonPointer = $data;
|
||||
data = 'rootData';
|
||||
} else {
|
||||
matches = $data.match(RELATIVE_JSON_POINTER);
|
||||
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
|
||||
up = +matches[1];
|
||||
jsonPointer = matches[2];
|
||||
if (jsonPointer == '#') {
|
||||
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
|
||||
return paths[lvl - up];
|
||||
}
|
||||
|
||||
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
|
||||
data = 'data' + ((lvl - up) || '');
|
||||
if (!jsonPointer) return data;
|
||||
}
|
||||
|
||||
var expr = data;
|
||||
var segments = jsonPointer.split('/');
|
||||
for (var i=0; i<segments.length; i++) {
|
||||
var segment = segments[i];
|
||||
if (segment) {
|
||||
data += getProperty(unescapeJsonPointer(segment));
|
||||
expr += ' && ' + data;
|
||||
}
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
|
||||
function joinPaths (a, b) {
|
||||
if (a == '""') return b;
|
||||
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
|
||||
}
|
||||
|
||||
|
||||
function unescapeFragment(str) {
|
||||
return unescapeJsonPointer(decodeURIComponent(str));
|
||||
}
|
||||
|
||||
|
||||
function escapeFragment(str) {
|
||||
return encodeURIComponent(escapeJsonPointer(str));
|
||||
}
|
||||
|
||||
|
||||
function escapeJsonPointer(str) {
|
||||
return str.replace(/~/g, '~0').replace(/\//g, '~1');
|
||||
}
|
||||
|
||||
|
||||
function unescapeJsonPointer(str) {
|
||||
return str.replace(/~1/g, '/').replace(/~0/g, '~');
|
||||
}
|
||||
213
electron/node_modules/ajv/lib/compile/util.ts
generated
vendored
Normal file
213
electron/node_modules/ajv/lib/compile/util.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
import type {AnySchema, EvaluatedProperties, EvaluatedItems} from "../types"
|
||||
import type {SchemaCxt, SchemaObjCxt} from "."
|
||||
import {_, getProperty, Code, Name, CodeGen} from "./codegen"
|
||||
import {_Code} from "./codegen/code"
|
||||
import type {Rule, ValidationRules} from "./rules"
|
||||
|
||||
// TODO refactor to use Set
|
||||
export function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {
|
||||
const hash: {[K in T]?: true} = {}
|
||||
for (const item of arr) hash[item] = true
|
||||
return hash
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
|
||||
export 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}"`)
|
||||
}
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export 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)}`
|
||||
}
|
||||
|
||||
export function unescapeFragment(str: string): string {
|
||||
return unescapeJsonPointer(decodeURIComponent(str))
|
||||
}
|
||||
|
||||
export function escapeFragment(str: string | number): string {
|
||||
return encodeURIComponent(escapeJsonPointer(str))
|
||||
}
|
||||
|
||||
export function escapeJsonPointer(str: string | number): string {
|
||||
if (typeof str == "number") return `${str}`
|
||||
return str.replace(/~/g, "~0").replace(/\//g, "~1")
|
||||
}
|
||||
|
||||
export function unescapeJsonPointer(str: string): string {
|
||||
return str.replace(/~1/g, "/").replace(/~0/g, "~")
|
||||
}
|
||||
|
||||
export function eachItem<T>(xs: T | T[], f: (x: T) => void): void {
|
||||
if (Array.isArray(xs)) {
|
||||
for (const x of xs) f(x)
|
||||
} else {
|
||||
f(xs)
|
||||
}
|
||||
}
|
||||
|
||||
type SomeEvaluated = EvaluatedProperties | EvaluatedItems
|
||||
|
||||
type MergeEvaluatedFunc<T extends SomeEvaluated> = (
|
||||
gen: CodeGen,
|
||||
from: Name | T,
|
||||
to: Name | Exclude<T, true> | undefined,
|
||||
toName?: typeof Name
|
||||
) => Name | T
|
||||
|
||||
interface MakeMergeFuncArgs<T extends SomeEvaluated> {
|
||||
mergeNames: (gen: CodeGen, from: Name, to: Name) => void
|
||||
mergeToName: (gen: CodeGen, from: T, to: Name) => void
|
||||
mergeValues: (from: T, to: Exclude<T, true>) => T
|
||||
resultToName: (gen: CodeGen, res?: T) => Name
|
||||
}
|
||||
|
||||
function makeMergeEvaluated<T extends SomeEvaluated>({
|
||||
mergeNames,
|
||||
mergeToName,
|
||||
mergeValues,
|
||||
resultToName,
|
||||
}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {
|
||||
return (gen, from, to, toName) => {
|
||||
const res =
|
||||
to === undefined
|
||||
? from
|
||||
: to instanceof Name
|
||||
? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
|
||||
: from instanceof Name
|
||||
? (mergeToName(gen, to, from), from)
|
||||
: mergeValues(from, to)
|
||||
return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res
|
||||
}
|
||||
}
|
||||
|
||||
interface MergeEvaluated {
|
||||
props: MergeEvaluatedFunc<EvaluatedProperties>
|
||||
items: MergeEvaluatedFunc<EvaluatedItems>
|
||||
}
|
||||
|
||||
export const mergeEvaluated: MergeEvaluated = {
|
||||
props: makeMergeEvaluated({
|
||||
mergeNames: (gen, from, to) =>
|
||||
gen.if(_`${to} !== true && ${from} !== undefined`, () => {
|
||||
gen.if(
|
||||
_`${from} === true`,
|
||||
() => gen.assign(to, true),
|
||||
() => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)
|
||||
)
|
||||
}),
|
||||
mergeToName: (gen, from, to) =>
|
||||
gen.if(_`${to} !== true`, () => {
|
||||
if (from === true) {
|
||||
gen.assign(to, true)
|
||||
} else {
|
||||
gen.assign(to, _`${to} || {}`)
|
||||
setEvaluated(gen, to, from)
|
||||
}
|
||||
}),
|
||||
mergeValues: (from, to) => (from === true ? true : {...from, ...to}),
|
||||
resultToName: evaluatedPropsToName,
|
||||
}),
|
||||
items: makeMergeEvaluated({
|
||||
mergeNames: (gen, from, to) =>
|
||||
gen.if(_`${to} !== true && ${from} !== undefined`, () =>
|
||||
gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)
|
||||
),
|
||||
mergeToName: (gen, from, to) =>
|
||||
gen.if(_`${to} !== true`, () =>
|
||||
gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)
|
||||
),
|
||||
mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
|
||||
resultToName: (gen, items) => gen.var("items", items),
|
||||
}),
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
|
||||
export function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {
|
||||
Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))
|
||||
}
|
||||
|
||||
const snippets: {[S in string]?: _Code} = {}
|
||||
|
||||
export 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)),
|
||||
})
|
||||
}
|
||||
|
||||
export enum Type {
|
||||
Num,
|
||||
Str,
|
||||
}
|
||||
|
||||
export function getErrorPath(
|
||||
dataProp: Name | string | number,
|
||||
dataPropType?: Type,
|
||||
jsPropertySyntax?: boolean
|
||||
): Code | string {
|
||||
// let path
|
||||
if (dataProp instanceof Name) {
|
||||
const isNumber = dataPropType === Type.Num
|
||||
return jsPropertySyntax
|
||||
? isNumber
|
||||
? _`"[" + ${dataProp} + "]"`
|
||||
: _`"['" + ${dataProp} + "']"`
|
||||
: isNumber
|
||||
? _`"/" + ${dataProp}`
|
||||
: _`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")` // TODO maybe use global escapePointer
|
||||
}
|
||||
return jsPropertySyntax ? getProperty(dataProp).toString() : "/" + escapeJsonPointer(dataProp)
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
22
electron/node_modules/ajv/lib/compile/validate/applicability.ts
generated
vendored
Normal file
22
electron/node_modules/ajv/lib/compile/validate/applicability.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import type {AnySchemaObject} from "../../types"
|
||||
import type {SchemaObjCxt} from ".."
|
||||
import type {JSONType, RuleGroup, Rule} from "../rules"
|
||||
|
||||
export function schemaHasRulesForType(
|
||||
{schema, self}: SchemaObjCxt,
|
||||
type: JSONType
|
||||
): boolean | undefined {
|
||||
const group = self.RULES.types[type]
|
||||
return group && group !== true && shouldUseGroup(schema, group)
|
||||
}
|
||||
|
||||
export function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {
|
||||
return group.rules.some((rule) => shouldUseRule(schema, rule))
|
||||
}
|
||||
|
||||
export function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {
|
||||
return (
|
||||
schema[rule.keyword] !== undefined ||
|
||||
rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)
|
||||
)
|
||||
}
|
||||
47
electron/node_modules/ajv/lib/compile/validate/boolSchema.ts
generated
vendored
Normal file
47
electron/node_modules/ajv/lib/compile/validate/boolSchema.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import type {KeywordErrorDefinition, KeywordErrorCxt} from "../../types"
|
||||
import type {SchemaCxt} from ".."
|
||||
import {reportError} from "../errors"
|
||||
import {_, Name} from "../codegen"
|
||||
import N from "../names"
|
||||
|
||||
const boolError: KeywordErrorDefinition = {
|
||||
message: "boolean schema is false",
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
230
electron/node_modules/ajv/lib/compile/validate/dataType.ts
generated
vendored
Normal file
230
electron/node_modules/ajv/lib/compile/validate/dataType.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import type {
|
||||
KeywordErrorDefinition,
|
||||
KeywordErrorCxt,
|
||||
ErrorObject,
|
||||
AnySchemaObject,
|
||||
} from "../../types"
|
||||
import type {SchemaObjCxt} from ".."
|
||||
import {isJSONType, JSONType} from "../rules"
|
||||
import {schemaHasRulesForType} from "./applicability"
|
||||
import {reportError} from "../errors"
|
||||
import {_, nil, and, not, operators, Code, Name} from "../codegen"
|
||||
import {toHash, schemaRefOrVal} from "../util"
|
||||
|
||||
export enum DataType {
|
||||
Correct,
|
||||
Wrong,
|
||||
}
|
||||
|
||||
export function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
|
||||
const types = getJSONTypes(schema.type)
|
||||
const hasNull = types.includes("null")
|
||||
if (hasNull) {
|
||||
if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
|
||||
} else {
|
||||
if (!types.length && schema.nullable !== undefined) {
|
||||
throw new Error('"nullable" cannot be used without "type"')
|
||||
}
|
||||
if (schema.nullable === true) types.push("null")
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
||||
export function getJSONTypes(ts: unknown | unknown[]): JSONType[] {
|
||||
const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []
|
||||
if (types.every(isJSONType)) return types
|
||||
throw new Error("type must be JSONType or JSONType[]: " + types.join(","))
|
||||
}
|
||||
|
||||
export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
|
||||
const {gen, data, opts} = it
|
||||
const coerceTo = coerceToTypes(types, opts.coerceTypes)
|
||||
const checkTypes =
|
||||
types.length > 0 &&
|
||||
!(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
|
||||
if (checkTypes) {
|
||||
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
|
||||
gen.if(wrongType, () => {
|
||||
if (coerceTo.length) coerceData(it, types, coerceTo)
|
||||
else reportTypeError(it)
|
||||
})
|
||||
}
|
||||
return checkTypes
|
||||
}
|
||||
|
||||
const COERCIBLE: Set<JSONType> = new Set(["string", "number", "integer", "boolean", "null"])
|
||||
function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] {
|
||||
return coerceTypes
|
||||
? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
|
||||
: []
|
||||
}
|
||||
|
||||
function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
|
||||
const {gen, data, opts} = it
|
||||
const dataType = gen.let("dataType", _`typeof ${data}`)
|
||||
const coerced = gen.let("coerced", _`undefined`)
|
||||
if (opts.coerceTypes === "array") {
|
||||
gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
|
||||
gen
|
||||
.assign(data, _`${data}[0]`)
|
||||
.assign(dataType, _`typeof ${data}`)
|
||||
.if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
|
||||
)
|
||||
}
|
||||
gen.if(_`${coerced} !== undefined`)
|
||||
for (const t of coerceTo) {
|
||||
if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
|
||||
coerceSpecificType(t)
|
||||
}
|
||||
}
|
||||
gen.else()
|
||||
reportTypeError(it)
|
||||
gen.endIf()
|
||||
|
||||
gen.if(_`${coerced} !== undefined`, () => {
|
||||
gen.assign(data, coerced)
|
||||
assignParentData(it, coerced)
|
||||
})
|
||||
|
||||
function coerceSpecificType(t: string): void {
|
||||
switch (t) {
|
||||
case "string":
|
||||
gen
|
||||
.elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
|
||||
.assign(coerced, _`"" + ${data}`)
|
||||
.elseIf(_`${data} === null`)
|
||||
.assign(coerced, _`""`)
|
||||
return
|
||||
case "number":
|
||||
gen
|
||||
.elseIf(
|
||||
_`${dataType} == "boolean" || ${data} === null
|
||||
|| (${dataType} == "string" && ${data} && ${data} == +${data})`
|
||||
)
|
||||
.assign(coerced, _`+${data}`)
|
||||
return
|
||||
case "integer":
|
||||
gen
|
||||
.elseIf(
|
||||
_`${dataType} === "boolean" || ${data} === null
|
||||
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
|
||||
)
|
||||
.assign(coerced, _`+${data}`)
|
||||
return
|
||||
case "boolean":
|
||||
gen
|
||||
.elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
|
||||
.assign(coerced, false)
|
||||
.elseIf(_`${data} === "true" || ${data} === 1`)
|
||||
.assign(coerced, true)
|
||||
return
|
||||
case "null":
|
||||
gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
|
||||
gen.assign(coerced, null)
|
||||
return
|
||||
|
||||
case "array":
|
||||
gen
|
||||
.elseIf(
|
||||
_`${dataType} === "string" || ${dataType} === "number"
|
||||
|| ${dataType} === "boolean" || ${data} === null`
|
||||
)
|
||||
.assign(coerced, _`[${data}]`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
|
||||
// TODO use gen.property
|
||||
gen.if(_`${parentData} !== undefined`, () =>
|
||||
gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
|
||||
)
|
||||
}
|
||||
|
||||
export function checkDataType(
|
||||
dataType: JSONType,
|
||||
data: Name,
|
||||
strictNums?: boolean | "log",
|
||||
correct = DataType.Correct
|
||||
): Code {
|
||||
const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
|
||||
let cond: Code
|
||||
switch (dataType) {
|
||||
case "null":
|
||||
return _`${data} ${EQ} null`
|
||||
case "array":
|
||||
cond = _`Array.isArray(${data})`
|
||||
break
|
||||
case "object":
|
||||
cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
|
||||
break
|
||||
case "integer":
|
||||
cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
|
||||
break
|
||||
case "number":
|
||||
cond = numCond()
|
||||
break
|
||||
default:
|
||||
return _`typeof ${data} ${EQ} ${dataType}`
|
||||
}
|
||||
return correct === DataType.Correct ? cond : not(cond)
|
||||
|
||||
function numCond(_cond: Code = nil): Code {
|
||||
return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
|
||||
}
|
||||
}
|
||||
|
||||
export function checkDataTypes(
|
||||
dataTypes: JSONType[],
|
||||
data: Name,
|
||||
strictNums?: boolean | "log",
|
||||
correct?: DataType
|
||||
): Code {
|
||||
if (dataTypes.length === 1) {
|
||||
return checkDataType(dataTypes[0], data, strictNums, correct)
|
||||
}
|
||||
let cond: Code
|
||||
const types = toHash(dataTypes)
|
||||
if (types.array && types.object) {
|
||||
const notObj = _`typeof ${data} != "object"`
|
||||
cond = types.null ? notObj : _`!${data} || ${notObj}`
|
||||
delete types.null
|
||||
delete types.array
|
||||
delete types.object
|
||||
} else {
|
||||
cond = nil
|
||||
}
|
||||
if (types.number) delete types.integer
|
||||
for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))
|
||||
return cond
|
||||
}
|
||||
|
||||
export type TypeError = ErrorObject<"type", {type: string}>
|
||||
|
||||
const typeError: KeywordErrorDefinition = {
|
||||
message: ({schema}) => `must be ${schema}`,
|
||||
params: ({schema, schemaValue}) =>
|
||||
typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,
|
||||
}
|
||||
|
||||
export function reportTypeError(it: SchemaObjCxt): void {
|
||||
const cxt = getTypeErrorContext(it)
|
||||
reportError(cxt, typeError)
|
||||
}
|
||||
|
||||
function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
|
||||
const {gen, data, schema} = it
|
||||
const schemaCode = schemaRefOrVal(it, schema, "type")
|
||||
return {
|
||||
gen,
|
||||
keyword: "type",
|
||||
data,
|
||||
schema: schema.type,
|
||||
schemaCode,
|
||||
schemaValue: schemaCode,
|
||||
parentSchema: schema,
|
||||
params: {},
|
||||
it,
|
||||
}
|
||||
}
|
||||
32
electron/node_modules/ajv/lib/compile/validate/defaults.ts
generated
vendored
Normal file
32
electron/node_modules/ajv/lib/compile/validate/defaults.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import type {SchemaObjCxt} from ".."
|
||||
import {_, getProperty, stringify} from "../codegen"
|
||||
import {checkStrictMode} from "../util"
|
||||
|
||||
export function assignDefaults(it: SchemaObjCxt, ty?: string): void {
|
||||
const {properties, items} = it.schema
|
||||
if (ty === "object" && properties) {
|
||||
for (const key in properties) {
|
||||
assignDefault(it, key, properties[key].default)
|
||||
}
|
||||
} else if (ty === "array" && Array.isArray(items)) {
|
||||
items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
|
||||
}
|
||||
}
|
||||
|
||||
function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
|
||||
const {gen, compositeRule, data, opts} = it
|
||||
if (defaultValue === undefined) return
|
||||
const childData = _`${data}${getProperty(prop)}`
|
||||
if (compositeRule) {
|
||||
checkStrictMode(it, `default is ignored for: ${childData}`)
|
||||
return
|
||||
}
|
||||
|
||||
let condition = _`${childData} === undefined`
|
||||
if (opts.useDefaults === "empty") {
|
||||
condition = _`${condition} || ${childData} === null || ${childData} === ""`
|
||||
}
|
||||
// `${childData} === undefined` +
|
||||
// (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
|
||||
gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
|
||||
}
|
||||
582
electron/node_modules/ajv/lib/compile/validate/index.ts
generated
vendored
Normal file
582
electron/node_modules/ajv/lib/compile/validate/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,582 @@
|
|||
import type {
|
||||
AddedKeywordDefinition,
|
||||
AnySchema,
|
||||
AnySchemaObject,
|
||||
KeywordErrorCxt,
|
||||
KeywordCxtParams,
|
||||
} from "../../types"
|
||||
import type {SchemaCxt, SchemaObjCxt} from ".."
|
||||
import type {InstanceOptions} from "../../core"
|
||||
import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
|
||||
import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
|
||||
import {shouldUseGroup, shouldUseRule} from "./applicability"
|
||||
import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
|
||||
import {assignDefaults} from "./defaults"
|
||||
import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
|
||||
import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
|
||||
import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
|
||||
import N from "../names"
|
||||
import {resolveUrl} from "../resolve"
|
||||
import {
|
||||
schemaRefOrVal,
|
||||
schemaHasRulesButRef,
|
||||
checkUnknownRules,
|
||||
checkStrictMode,
|
||||
unescapeJsonPointer,
|
||||
mergeEvaluated,
|
||||
} from "../util"
|
||||
import type {JSONType, Rule, RuleGroup} from "../rules"
|
||||
import {
|
||||
ErrorPaths,
|
||||
reportError,
|
||||
reportExtraError,
|
||||
resetErrorsCount,
|
||||
keyword$DataError,
|
||||
} from "../errors"
|
||||
|
||||
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
|
||||
export function validateFunctionCode(it: SchemaCxt): void {
|
||||
if (isSchemaObj(it)) {
|
||||
checkKeywords(it)
|
||||
if (schemaCxtHasRules(it)) {
|
||||
topSchemaObjCode(it)
|
||||
return
|
||||
}
|
||||
}
|
||||
validateFunction(it, () => topBoolOrEmptySchema(it))
|
||||
}
|
||||
|
||||
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)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function destructureValCxt(opts: InstanceOptions): Code {
|
||||
return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
|
||||
N.data
|
||||
}${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
|
||||
}
|
||||
|
||||
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, _`{}`)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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`))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// schema compilation - this function is used recursively to generate code for sub-schemas
|
||||
function subschemaCode(it: SchemaCxt, valid: Name): void {
|
||||
if (isSchemaObj(it)) {
|
||||
checkKeywords(it)
|
||||
if (schemaCxtHasRules(it)) {
|
||||
subSchemaObjCode(it, valid)
|
||||
return
|
||||
}
|
||||
}
|
||||
boolOrEmptySchema(it, valid)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
|
||||
return typeof it.schema != "boolean"
|
||||
}
|
||||
|
||||
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}`)
|
||||
}
|
||||
|
||||
function checkKeywords(it: SchemaObjCxt): void {
|
||||
checkUnknownRules(it)
|
||||
checkRefsAndKeywords(it)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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}"`)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
function updateContext(it: SchemaObjCxt): void {
|
||||
const schId = it.schema[it.opts.schemaId]
|
||||
if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
|
||||
}
|
||||
|
||||
function checkAsyncSchema(it: SchemaObjCxt): void {
|
||||
if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
|
||||
}
|
||||
|
||||
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)`)
|
||||
}
|
||||
}
|
||||
|
||||
function returnResults(it: SchemaCxt): void {
|
||||
const {gen, schemaEnv, validateName, ValidationError, opts} = it
|
||||
if (schemaEnv.$async) {
|
||||
// TODO assign unevaluated
|
||||
gen.if(
|
||||
_`${N.errors} === 0`,
|
||||
() => gen.return(N.data),
|
||||
() => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
|
||||
)
|
||||
} else {
|
||||
gen.assign(_`${validateName}.errors`, N.vErrors)
|
||||
if (opts.unevaluated) assignEvaluated(it)
|
||||
gen.return(_`${N.errors} === 0`)
|
||||
}
|
||||
}
|
||||
|
||||
function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
|
||||
if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
|
||||
if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
|
||||
}
|
||||
|
||||
function schemaKeywords(
|
||||
it: SchemaObjCxt,
|
||||
types: JSONType[],
|
||||
typeErrors: boolean,
|
||||
errsCount?: Name
|
||||
): void {
|
||||
const {gen, schema, data, allErrors, opts, self} = it
|
||||
const {RULES} = self
|
||||
if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
|
||||
gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
|
||||
return
|
||||
}
|
||||
if (!opts.jtd) checkStrictTypes(it, types)
|
||||
gen.block(() => {
|
||||
for (const group of RULES.rules) groupKeywords(group)
|
||||
groupKeywords(RULES.post)
|
||||
})
|
||||
|
||||
function groupKeywords(group: RuleGroup): void {
|
||||
if (!shouldUseGroup(schema, group)) return
|
||||
if (group.type) {
|
||||
gen.if(checkDataType(group.type, data, opts.strictNumbers))
|
||||
iterateKeywords(it, group)
|
||||
if (types.length === 1 && types[0] === group.type && typeErrors) {
|
||||
gen.else()
|
||||
reportTypeError(it)
|
||||
}
|
||||
gen.endIf()
|
||||
} else {
|
||||
iterateKeywords(it, group)
|
||||
}
|
||||
// TODO make it "ok" call?
|
||||
if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
|
||||
}
|
||||
}
|
||||
|
||||
function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
|
||||
const {
|
||||
gen,
|
||||
schema,
|
||||
opts: {useDefaults},
|
||||
} = it
|
||||
if (useDefaults) assignDefaults(it, group.type)
|
||||
gen.block(() => {
|
||||
for (const rule of group.rules) {
|
||||
if (shouldUseRule(schema, rule)) {
|
||||
keywordCode(it, rule.keyword, rule.definition, group.type)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
|
||||
if (it.schemaEnv.meta || !it.opts.strictTypes) return
|
||||
checkContextTypes(it, types)
|
||||
if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
|
||||
checkKeywordTypes(it, it.dataTypes)
|
||||
}
|
||||
|
||||
function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
|
||||
if (!types.length) return
|
||||
if (!it.dataTypes.length) {
|
||||
it.dataTypes = types
|
||||
return
|
||||
}
|
||||
types.forEach((t) => {
|
||||
if (!includesType(it.dataTypes, t)) {
|
||||
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
|
||||
}
|
||||
})
|
||||
narrowSchemaTypes(it, types)
|
||||
}
|
||||
|
||||
function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
|
||||
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
|
||||
strictTypesError(it, "use allowUnionTypes to allow union type keyword")
|
||||
}
|
||||
}
|
||||
|
||||
function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
|
||||
const rules = it.self.RULES.all
|
||||
for (const keyword in rules) {
|
||||
const rule = rules[keyword]
|
||||
if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
|
||||
const {type} = rule.definition
|
||||
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
|
||||
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
|
||||
return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
|
||||
}
|
||||
|
||||
function includesType(ts: JSONType[], t: JSONType): boolean {
|
||||
return ts.includes(t) || (t === "integer" && ts.includes("number"))
|
||||
}
|
||||
|
||||
function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
|
||||
const ts: JSONType[] = []
|
||||
for (const t of it.dataTypes) {
|
||||
if (includesType(withTypes, t)) ts.push(t)
|
||||
else if (withTypes.includes("integer") && t === "number") ts.push("integer")
|
||||
}
|
||||
it.dataTypes = ts
|
||||
}
|
||||
|
||||
function strictTypesError(it: SchemaObjCxt, msg: string): void {
|
||||
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
|
||||
msg += ` at "${schemaPath}" (strictTypes)`
|
||||
checkStrictMode(it, msg, it.opts.strictTypes)
|
||||
}
|
||||
|
||||
export class KeywordCxt implements KeywordErrorCxt {
|
||||
readonly gen: CodeGen
|
||||
readonly allErrors?: boolean
|
||||
readonly keyword: string
|
||||
readonly data: Name // Name referencing the current level of the data instance
|
||||
readonly $data?: string | false
|
||||
schema: any // keyword value in the schema
|
||||
readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
|
||||
readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
|
||||
readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
|
||||
readonly parentSchema: AnySchemaObject
|
||||
readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
|
||||
// requires option trackErrors in keyword definition
|
||||
params: KeywordCxtParams // object to pass parameters to error messages from keyword code
|
||||
readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
|
||||
readonly def: AddedKeywordDefinition
|
||||
|
||||
constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
|
||||
validateKeywordUsage(it, def, keyword)
|
||||
this.gen = it.gen
|
||||
this.allErrors = it.allErrors
|
||||
this.keyword = keyword
|
||||
this.data = it.data
|
||||
this.schema = it.schema[keyword]
|
||||
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
|
||||
this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
|
||||
this.schemaType = def.schemaType
|
||||
this.parentSchema = it.schema
|
||||
this.params = {}
|
||||
this.it = it
|
||||
this.def = def
|
||||
|
||||
if (this.$data) {
|
||||
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
|
||||
} else {
|
||||
this.schemaCode = this.schemaValue
|
||||
if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
|
||||
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
|
||||
}
|
||||
}
|
||||
|
||||
if ("code" in def ? def.trackErrors : def.errors !== false) {
|
||||
this.errsCount = it.gen.const("_errs", N.errors)
|
||||
}
|
||||
}
|
||||
|
||||
result(condition: Code, successAction?: () => void, failAction?: () => void): void {
|
||||
this.failResult(not(condition), successAction, failAction)
|
||||
}
|
||||
|
||||
failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
|
||||
this.gen.if(condition)
|
||||
if (failAction) failAction()
|
||||
else this.error()
|
||||
if (successAction) {
|
||||
this.gen.else()
|
||||
successAction()
|
||||
if (this.allErrors) this.gen.endIf()
|
||||
} else {
|
||||
if (this.allErrors) this.gen.endIf()
|
||||
else this.gen.else()
|
||||
}
|
||||
}
|
||||
|
||||
pass(condition: Code, failAction?: () => void): void {
|
||||
this.failResult(not(condition), undefined, failAction)
|
||||
}
|
||||
|
||||
fail(condition?: Code): void {
|
||||
if (condition === undefined) {
|
||||
this.error()
|
||||
if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
|
||||
return
|
||||
}
|
||||
this.gen.if(condition)
|
||||
this.error()
|
||||
if (this.allErrors) this.gen.endIf()
|
||||
else this.gen.else()
|
||||
}
|
||||
|
||||
fail$data(condition: Code): void {
|
||||
if (!this.$data) return this.fail(condition)
|
||||
const {schemaCode} = this
|
||||
this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
|
||||
}
|
||||
|
||||
error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
|
||||
if (errorParams) {
|
||||
this.setParams(errorParams)
|
||||
this._error(append, errorPaths)
|
||||
this.setParams({})
|
||||
return
|
||||
}
|
||||
this._error(append, errorPaths)
|
||||
}
|
||||
|
||||
private _error(append?: boolean, errorPaths?: ErrorPaths): void {
|
||||
;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
|
||||
}
|
||||
|
||||
$dataError(): void {
|
||||
reportError(this, this.def.$dataError || keyword$DataError)
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
|
||||
resetErrorsCount(this.gen, this.errsCount)
|
||||
}
|
||||
|
||||
ok(cond: Code | boolean): void {
|
||||
if (!this.allErrors) this.gen.if(cond)
|
||||
}
|
||||
|
||||
setParams(obj: KeywordCxtParams, assign?: true): void {
|
||||
if (assign) Object.assign(this.params, obj)
|
||||
else this.params = obj
|
||||
}
|
||||
|
||||
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
|
||||
this.gen.block(() => {
|
||||
this.check$data(valid, $dataValid)
|
||||
codeBlock()
|
||||
})
|
||||
}
|
||||
|
||||
check$data(valid: Name = nil, $dataValid: Code = nil): void {
|
||||
if (!this.$data) return
|
||||
const {gen, schemaCode, schemaType, def} = this
|
||||
gen.if(or(_`${schemaCode} === undefined`, $dataValid))
|
||||
if (valid !== nil) gen.assign(valid, true)
|
||||
if (schemaType.length || def.validateSchema) {
|
||||
gen.elseIf(this.invalid$data())
|
||||
this.$dataError()
|
||||
if (valid !== nil) gen.assign(valid, false)
|
||||
}
|
||||
gen.else()
|
||||
}
|
||||
|
||||
invalid$data(): Code {
|
||||
const {gen, schemaCode, schemaType, def, it} = this
|
||||
return or(wrong$DataType(), invalid$DataSchema())
|
||||
|
||||
function wrong$DataType(): Code {
|
||||
if (schemaType.length) {
|
||||
/* istanbul ignore if */
|
||||
if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
|
||||
const st = Array.isArray(schemaType) ? schemaType : [schemaType]
|
||||
return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
function invalid$DataSchema(): Code {
|
||||
if (def.validateSchema) {
|
||||
const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
|
||||
return _`!${validateSchemaRef}(${schemaCode})`
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
|
||||
const subschema = getSubschema(this.it, appl)
|
||||
extendSubschemaData(subschema, this.it, appl)
|
||||
extendSubschemaMode(subschema, appl)
|
||||
const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
|
||||
subschemaCode(nextContext, valid)
|
||||
return nextContext
|
||||
}
|
||||
|
||||
mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
|
||||
const {it, gen} = this
|
||||
if (!it.opts.unevaluated) return
|
||||
if (it.props !== true && schemaCxt.props !== undefined) {
|
||||
it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
|
||||
}
|
||||
if (it.items !== true && schemaCxt.items !== undefined) {
|
||||
it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
|
||||
}
|
||||
}
|
||||
|
||||
mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
|
||||
const {it, gen} = this
|
||||
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
|
||||
gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function keywordCode(
|
||||
it: SchemaObjCxt,
|
||||
keyword: string,
|
||||
def: AddedKeywordDefinition,
|
||||
ruleType?: JSONType
|
||||
): void {
|
||||
const cxt = new KeywordCxt(it, def, keyword)
|
||||
if ("code" in def) {
|
||||
def.code(cxt, ruleType)
|
||||
} else if (cxt.$data && def.validate) {
|
||||
funcKeywordCode(cxt, def)
|
||||
} else if ("macro" in def) {
|
||||
macroKeywordCode(cxt, def)
|
||||
} else if (def.compile || def.validate) {
|
||||
funcKeywordCode(cxt, def)
|
||||
}
|
||||
}
|
||||
|
||||
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
|
||||
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
|
||||
export function getData(
|
||||
$data: string,
|
||||
{dataLevel, dataNames, dataPathArr}: SchemaCxt
|
||||
): Code | number {
|
||||
let jsonPointer
|
||||
let data: Code
|
||||
if ($data === "") return N.rootData
|
||||
if ($data[0] === "/") {
|
||||
if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
|
||||
jsonPointer = $data
|
||||
data = N.rootData
|
||||
} else {
|
||||
const matches = RELATIVE_JSON_POINTER.exec($data)
|
||||
if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
|
||||
const up: number = +matches[1]
|
||||
jsonPointer = matches[2]
|
||||
if (jsonPointer === "#") {
|
||||
if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
|
||||
return dataPathArr[dataLevel - up]
|
||||
}
|
||||
if (up > dataLevel) throw new Error(errorMsg("data", up))
|
||||
data = dataNames[dataLevel - up]
|
||||
if (!jsonPointer) return data
|
||||
}
|
||||
|
||||
let expr = data
|
||||
const segments = jsonPointer.split("/")
|
||||
for (const segment of segments) {
|
||||
if (segment) {
|
||||
data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
|
||||
expr = _`${expr} && ${data}`
|
||||
}
|
||||
}
|
||||
return expr
|
||||
|
||||
function errorMsg(pointerType: string, up: number): string {
|
||||
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
|
||||
}
|
||||
}
|
||||
171
electron/node_modules/ajv/lib/compile/validate/keyword.ts
generated
vendored
Normal file
171
electron/node_modules/ajv/lib/compile/validate/keyword.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
import type {KeywordCxt} from "."
|
||||
import type {
|
||||
AnySchema,
|
||||
SchemaValidateFunction,
|
||||
AnyValidateFunction,
|
||||
AddedKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
} from "../../types"
|
||||
import type {SchemaObjCxt} from ".."
|
||||
import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen"
|
||||
import N from "../names"
|
||||
import type {JSONType} from "../rules"
|
||||
import {callValidateCode} from "../../vocabularies/code"
|
||||
import {extendErrors} from "../errors"
|
||||
|
||||
type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction
|
||||
|
||||
export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
|
||||
const {gen, keyword, schema, parentSchema, it} = cxt
|
||||
const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
|
||||
const schemaRef = useKeyword(gen, keyword, macroSchema)
|
||||
if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)
|
||||
|
||||
const valid = gen.name("valid")
|
||||
cxt.subschema(
|
||||
{
|
||||
schema: macroSchema,
|
||||
schemaPath: nil,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
||||
topSchemaRef: schemaRef,
|
||||
compositeRule: true,
|
||||
},
|
||||
valid
|
||||
)
|
||||
cxt.pass(valid, () => cxt.error(true))
|
||||
}
|
||||
|
||||
export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
|
||||
const {gen, keyword, schema, parentSchema, $data, it} = cxt
|
||||
checkAsyncKeyword(it, def)
|
||||
const validate =
|
||||
!$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
|
||||
const validateRef = useKeyword(gen, keyword, validate)
|
||||
const valid = gen.let("valid")
|
||||
cxt.block$data(valid, validateKeyword)
|
||||
cxt.ok(def.valid ?? valid)
|
||||
|
||||
function validateKeyword(): void {
|
||||
if (def.errors === false) {
|
||||
assignValid()
|
||||
if (def.modifying) modifyData(cxt)
|
||||
reportErrs(() => cxt.error())
|
||||
} else {
|
||||
const ruleErrs = def.async ? validateAsync() : validateSync()
|
||||
if (def.modifying) modifyData(cxt)
|
||||
reportErrs(() => addErrs(cxt, ruleErrs))
|
||||
}
|
||||
}
|
||||
|
||||
function validateAsync(): Name {
|
||||
const ruleErrs = gen.let("ruleErrs", null)
|
||||
gen.try(
|
||||
() => assignValid(_`await `),
|
||||
(e) =>
|
||||
gen.assign(valid, false).if(
|
||||
_`${e} instanceof ${it.ValidationError as Name}`,
|
||||
() => gen.assign(ruleErrs, _`${e}.errors`),
|
||||
() => gen.throw(e)
|
||||
)
|
||||
)
|
||||
return ruleErrs
|
||||
}
|
||||
|
||||
function validateSync(): Code {
|
||||
const validateErrs = _`${validateRef}.errors`
|
||||
gen.assign(validateErrs, null)
|
||||
assignValid(nil)
|
||||
return validateErrs
|
||||
}
|
||||
|
||||
function assignValid(_await: Code = def.async ? _`await ` : nil): void {
|
||||
const passCxt = it.opts.passContext ? N.this : N.self
|
||||
const passSchema = !(("compile" in def && !$data) || def.schema === false)
|
||||
gen.assign(
|
||||
valid,
|
||||
_`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
|
||||
def.modifying
|
||||
)
|
||||
}
|
||||
|
||||
function reportErrs(errors: () => void): void {
|
||||
gen.if(not(def.valid ?? valid), errors)
|
||||
}
|
||||
}
|
||||
|
||||
function modifyData(cxt: KeywordCxt): void {
|
||||
const {gen, data, it} = cxt
|
||||
gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))
|
||||
}
|
||||
|
||||
function addErrs(cxt: KeywordCxt, errs: Code): void {
|
||||
const {gen} = cxt
|
||||
gen.if(
|
||||
_`Array.isArray(${errs})`,
|
||||
() => {
|
||||
gen
|
||||
.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
|
||||
.assign(N.errors, _`${N.vErrors}.length`)
|
||||
extendErrors(cxt)
|
||||
},
|
||||
() => cxt.error()
|
||||
)
|
||||
}
|
||||
|
||||
function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
|
||||
if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
|
||||
}
|
||||
|
||||
function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
|
||||
if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
|
||||
return gen.scopeValue(
|
||||
"keyword",
|
||||
typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
|
||||
)
|
||||
}
|
||||
|
||||
export function validSchemaType(
|
||||
schema: unknown,
|
||||
schemaType: JSONType[],
|
||||
allowUndefined = false
|
||||
): boolean {
|
||||
// TODO add tests
|
||||
return (
|
||||
!schemaType.length ||
|
||||
schemaType.some((st) =>
|
||||
st === "array"
|
||||
? Array.isArray(schema)
|
||||
: st === "object"
|
||||
? schema && typeof schema == "object" && !Array.isArray(schema)
|
||||
: typeof schema == st || (allowUndefined && typeof schema == "undefined")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function validateKeywordUsage(
|
||||
{schema, opts, self, errSchemaPath}: SchemaObjCxt,
|
||||
def: AddedKeywordDefinition,
|
||||
keyword: string
|
||||
): void {
|
||||
/* istanbul ignore if */
|
||||
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
|
||||
throw new Error("ajv implementation error")
|
||||
}
|
||||
|
||||
const deps = def.dependencies
|
||||
if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
|
||||
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
|
||||
}
|
||||
|
||||
if (def.validateSchema) {
|
||||
const valid = def.validateSchema(schema[keyword])
|
||||
if (!valid) {
|
||||
const msg =
|
||||
`keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
|
||||
self.errorsText(def.validateSchema.errors)
|
||||
if (opts.validateSchema === "log") self.logger.error(msg)
|
||||
else throw new Error(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
135
electron/node_modules/ajv/lib/compile/validate/subschema.ts
generated
vendored
Normal file
135
electron/node_modules/ajv/lib/compile/validate/subschema.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import type {AnySchema} from "../../types"
|
||||
import type {SchemaObjCxt} from ".."
|
||||
import {_, str, getProperty, Code, Name} from "../codegen"
|
||||
import {escapeFragment, getErrorPath, Type} from "../util"
|
||||
import type {JSONType} from "../rules"
|
||||
|
||||
export interface SubschemaContext {
|
||||
// TODO use Optional? align with SchemCxt property types
|
||||
schema: AnySchema
|
||||
schemaPath: Code
|
||||
errSchemaPath: string
|
||||
topSchemaRef?: Code
|
||||
errorPath?: Code
|
||||
dataLevel?: number
|
||||
dataTypes?: JSONType[]
|
||||
data?: Name
|
||||
parentData?: Name
|
||||
parentDataProperty?: Code | number
|
||||
dataNames?: Name[]
|
||||
dataPathArr?: (Code | number)[]
|
||||
propertyName?: Name
|
||||
jtdDiscriminator?: string
|
||||
jtdMetadata?: boolean
|
||||
compositeRule?: true
|
||||
createErrors?: boolean
|
||||
allErrors?: boolean
|
||||
}
|
||||
|
||||
export type SubschemaArgs = Partial<{
|
||||
keyword: string
|
||||
schemaProp: string | number
|
||||
schema: AnySchema
|
||||
schemaPath: Code
|
||||
errSchemaPath: string
|
||||
topSchemaRef: Code
|
||||
data: Name | Code
|
||||
dataProp: Code | string | number
|
||||
dataTypes: JSONType[]
|
||||
definedProperties: Set<string>
|
||||
propertyName: Name
|
||||
dataPropType: Type
|
||||
jtdDiscriminator: string
|
||||
jtdMetadata: boolean
|
||||
compositeRule: true
|
||||
createErrors: boolean
|
||||
allErrors: boolean
|
||||
}>
|
||||
|
||||
export function getSubschema(
|
||||
it: SchemaObjCxt,
|
||||
{keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
|
||||
): SubschemaContext {
|
||||
if (keyword !== undefined && schema !== undefined) {
|
||||
throw new Error('both "keyword" and "schema" passed, only one allowed')
|
||||
}
|
||||
|
||||
if (keyword !== undefined) {
|
||||
const sch = it.schema[keyword]
|
||||
return schemaProp === undefined
|
||||
? {
|
||||
schema: sch,
|
||||
schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
||||
}
|
||||
: {
|
||||
schema: sch[schemaProp],
|
||||
schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
|
||||
errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
|
||||
}
|
||||
}
|
||||
|
||||
if (schema !== undefined) {
|
||||
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
|
||||
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
|
||||
}
|
||||
return {
|
||||
schema,
|
||||
schemaPath,
|
||||
topSchemaRef,
|
||||
errSchemaPath,
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('either "keyword" or "schema" must be passed')
|
||||
}
|
||||
|
||||
export function extendSubschemaData(
|
||||
subschema: SubschemaContext,
|
||||
it: SchemaObjCxt,
|
||||
{dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
|
||||
): void {
|
||||
if (data !== undefined && dataProp !== undefined) {
|
||||
throw new Error('both "data" and "dataProp" passed, only one allowed')
|
||||
}
|
||||
|
||||
const {gen} = it
|
||||
|
||||
if (dataProp !== undefined) {
|
||||
const {errorPath, dataPathArr, opts} = it
|
||||
const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
|
||||
dataContextProps(nextData)
|
||||
subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
|
||||
subschema.parentDataProperty = _`${dataProp}`
|
||||
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
|
||||
}
|
||||
|
||||
if (data !== undefined) {
|
||||
const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
|
||||
dataContextProps(nextData)
|
||||
if (propertyName !== undefined) subschema.propertyName = propertyName
|
||||
// TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
|
||||
}
|
||||
|
||||
if (dataTypes) subschema.dataTypes = dataTypes
|
||||
|
||||
function dataContextProps(_nextData: Name): void {
|
||||
subschema.data = _nextData
|
||||
subschema.dataLevel = it.dataLevel + 1
|
||||
subschema.dataTypes = []
|
||||
it.definedProperties = new Set<string>()
|
||||
subschema.parentData = it.data
|
||||
subschema.dataNames = [...it.dataNames, _nextData]
|
||||
}
|
||||
}
|
||||
|
||||
export function extendSubschemaMode(
|
||||
subschema: SubschemaContext,
|
||||
{jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
|
||||
): void {
|
||||
if (compositeRule !== undefined) subschema.compositeRule = compositeRule
|
||||
if (createErrors !== undefined) subschema.createErrors = createErrors
|
||||
if (allErrors !== undefined) subschema.allErrors = allErrors
|
||||
subschema.jtdDiscriminator = jtdDiscriminator // not inherited
|
||||
subschema.jtdMetadata = jtdMetadata // not inherited
|
||||
}
|
||||
892
electron/node_modules/ajv/lib/core.ts
generated
vendored
Normal file
892
electron/node_modules/ajv/lib/core.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,892 @@
|
|||
export {
|
||||
Format,
|
||||
FormatDefinition,
|
||||
AsyncFormatDefinition,
|
||||
KeywordDefinition,
|
||||
KeywordErrorDefinition,
|
||||
CodeKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
Vocabulary,
|
||||
Schema,
|
||||
SchemaObject,
|
||||
AnySchemaObject,
|
||||
AsyncSchema,
|
||||
AnySchema,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
AnyValidateFunction,
|
||||
ErrorObject,
|
||||
ErrorNoParams,
|
||||
} from "./types"
|
||||
|
||||
export {SchemaCxt, SchemaObjCxt} from "./compile"
|
||||
export interface Plugin<Opts> {
|
||||
(ajv: Ajv, options?: Opts): Ajv
|
||||
[prop: string]: any
|
||||
}
|
||||
|
||||
export {KeywordCxt} from "./compile/validate"
|
||||
export {DefinedError} from "./vocabularies/errors"
|
||||
export {JSONType} from "./compile/rules"
|
||||
export {JSONSchemaType} from "./types/json-schema"
|
||||
export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
|
||||
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
|
||||
|
||||
import type {
|
||||
Schema,
|
||||
AnySchema,
|
||||
AnySchemaObject,
|
||||
SchemaObject,
|
||||
AsyncSchema,
|
||||
Vocabulary,
|
||||
KeywordDefinition,
|
||||
AddedKeywordDefinition,
|
||||
AnyValidateFunction,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
ErrorObject,
|
||||
Format,
|
||||
AddedFormat,
|
||||
RegExpEngine,
|
||||
UriResolver,
|
||||
} from "./types"
|
||||
import type {JSONSchemaType} from "./types/json-schema"
|
||||
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
|
||||
import ValidationError from "./runtime/validation_error"
|
||||
import MissingRefError from "./compile/ref_error"
|
||||
import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
|
||||
import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
|
||||
import {Code, ValueScope} from "./compile/codegen"
|
||||
import {normalizeId, getSchemaRefs} from "./compile/resolve"
|
||||
import {getJSONTypes} from "./compile/validate/dataType"
|
||||
import {eachItem} from "./compile/util"
|
||||
import * as $dataRefSchema from "./refs/data.json"
|
||||
|
||||
import DefaultUriResolver from "./runtime/uri"
|
||||
|
||||
const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
|
||||
defaultRegExp.code = "new RegExp"
|
||||
|
||||
const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
|
||||
const EXT_SCOPE_NAMES = new Set([
|
||||
"validate",
|
||||
"serialize",
|
||||
"parse",
|
||||
"wrapper",
|
||||
"root",
|
||||
"schema",
|
||||
"keyword",
|
||||
"pattern",
|
||||
"formats",
|
||||
"validate$data",
|
||||
"func",
|
||||
"obj",
|
||||
"Error",
|
||||
])
|
||||
|
||||
export type Options = CurrentOptions & DeprecatedOptions
|
||||
|
||||
export interface CurrentOptions {
|
||||
// strict mode options (NEW)
|
||||
strict?: boolean | "log"
|
||||
strictSchema?: boolean | "log"
|
||||
strictNumbers?: boolean | "log"
|
||||
strictTypes?: boolean | "log"
|
||||
strictTuples?: boolean | "log"
|
||||
strictRequired?: boolean | "log"
|
||||
allowMatchingProperties?: boolean // disables a strict mode restriction
|
||||
allowUnionTypes?: boolean
|
||||
validateFormats?: boolean
|
||||
// validation and reporting options:
|
||||
$data?: boolean
|
||||
allErrors?: boolean
|
||||
verbose?: boolean
|
||||
discriminator?: boolean
|
||||
unicodeRegExp?: boolean
|
||||
timestamp?: "string" | "date" // JTD only
|
||||
parseDate?: boolean // JTD only
|
||||
allowDate?: boolean // JTD only
|
||||
specialNumbers?: "fast" | "null" // JTD only
|
||||
$comment?:
|
||||
| true
|
||||
| ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
|
||||
formats?: {[Name in string]?: Format}
|
||||
keywords?: Vocabulary
|
||||
schemas?: AnySchema[] | {[Key in string]?: AnySchema}
|
||||
logger?: Logger | false
|
||||
loadSchema?: (uri: string) => Promise<AnySchemaObject>
|
||||
// options to modify validated data:
|
||||
removeAdditional?: boolean | "all" | "failing"
|
||||
useDefaults?: boolean | "empty"
|
||||
coerceTypes?: boolean | "array"
|
||||
// advanced options:
|
||||
next?: boolean // NEW
|
||||
unevaluated?: boolean // NEW
|
||||
dynamicRef?: boolean // NEW
|
||||
schemaId?: "id" | "$id"
|
||||
jtd?: boolean // NEW
|
||||
meta?: SchemaObject | boolean
|
||||
defaultMeta?: string | AnySchemaObject
|
||||
validateSchema?: boolean | "log"
|
||||
addUsedSchema?: boolean
|
||||
inlineRefs?: boolean | number
|
||||
passContext?: boolean
|
||||
loopRequired?: number
|
||||
loopEnum?: number // NEW
|
||||
ownProperties?: boolean
|
||||
multipleOfPrecision?: number
|
||||
int32range?: boolean // JTD only
|
||||
messages?: boolean
|
||||
code?: CodeOptions // NEW
|
||||
uriResolver?: UriResolver
|
||||
}
|
||||
|
||||
export interface CodeOptions {
|
||||
es5?: boolean
|
||||
esm?: boolean
|
||||
lines?: boolean
|
||||
optimize?: boolean | number
|
||||
formats?: Code // code to require (or construct) map of available formats - for standalone code
|
||||
source?: boolean
|
||||
process?: (code: string, schema?: SchemaEnv) => string
|
||||
regExp?: RegExpEngine
|
||||
}
|
||||
|
||||
interface InstanceCodeOptions extends CodeOptions {
|
||||
regExp: RegExpEngine
|
||||
optimize: number
|
||||
}
|
||||
|
||||
interface DeprecatedOptions {
|
||||
/** @deprecated */
|
||||
ignoreKeywordsWithRef?: boolean
|
||||
/** @deprecated */
|
||||
jsPropertySyntax?: boolean // added instead of jsonPointers
|
||||
/** @deprecated */
|
||||
unicode?: boolean
|
||||
}
|
||||
|
||||
interface RemovedOptions {
|
||||
format?: boolean
|
||||
errorDataPath?: "object" | "property"
|
||||
nullable?: boolean // "nullable" keyword is supported by default
|
||||
jsonPointers?: boolean
|
||||
extendRefs?: true | "ignore" | "fail"
|
||||
missingRefs?: true | "ignore" | "fail"
|
||||
processCode?: (code: string, schema?: SchemaEnv) => string
|
||||
sourceCode?: boolean
|
||||
strictDefaults?: boolean
|
||||
strictKeywords?: boolean
|
||||
uniqueItems?: boolean
|
||||
unknownFormats?: true | string[] | "ignore"
|
||||
cache?: any
|
||||
serialize?: (schema: AnySchema) => unknown
|
||||
ajvErrors?: boolean
|
||||
}
|
||||
|
||||
type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
|
||||
[K in keyof T]-?: string | undefined
|
||||
}
|
||||
|
||||
const removedOptions: OptionsInfo<RemovedOptions> = {
|
||||
errorDataPath: "",
|
||||
format: "`validateFormats: false` can be used instead.",
|
||||
nullable: '"nullable" keyword is supported by default.',
|
||||
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
||||
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
||||
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
||||
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
||||
sourceCode: "Use option `code: {source: true}`",
|
||||
strictDefaults: "It is default now, see option `strict`.",
|
||||
strictKeywords: "It is default now, see option `strict`.",
|
||||
uniqueItems: '"uniqueItems" keyword is always validated.',
|
||||
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
||||
cache: "Map is used as cache, schema object as key.",
|
||||
serialize: "Map is used as cache, schema object as key.",
|
||||
ajvErrors: "It is default now.",
|
||||
}
|
||||
|
||||
const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
|
||||
ignoreKeywordsWithRef: "",
|
||||
jsPropertySyntax: "",
|
||||
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
|
||||
}
|
||||
|
||||
type RequiredInstanceOptions = {
|
||||
[K in
|
||||
| "strictSchema"
|
||||
| "strictNumbers"
|
||||
| "strictTypes"
|
||||
| "strictTuples"
|
||||
| "strictRequired"
|
||||
| "inlineRefs"
|
||||
| "loopRequired"
|
||||
| "loopEnum"
|
||||
| "meta"
|
||||
| "messages"
|
||||
| "schemaId"
|
||||
| "addUsedSchema"
|
||||
| "validateSchema"
|
||||
| "validateFormats"
|
||||
| "int32range"
|
||||
| "unicodeRegExp"
|
||||
| "uriResolver"]: NonNullable<Options[K]>
|
||||
} & {code: InstanceCodeOptions}
|
||||
|
||||
export type InstanceOptions = Options & RequiredInstanceOptions
|
||||
|
||||
const MAX_EXPRESSION = 200
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
function requiredOptions(o: Options): RequiredInstanceOptions {
|
||||
const s = o.strict
|
||||
const _optz = o.code?.optimize
|
||||
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
|
||||
const regExp = o.code?.regExp ?? defaultRegExp
|
||||
const uriResolver = o.uriResolver ?? DefaultUriResolver
|
||||
return {
|
||||
strictSchema: o.strictSchema ?? s ?? true,
|
||||
strictNumbers: o.strictNumbers ?? s ?? true,
|
||||
strictTypes: o.strictTypes ?? s ?? "log",
|
||||
strictTuples: o.strictTuples ?? s ?? "log",
|
||||
strictRequired: o.strictRequired ?? s ?? false,
|
||||
code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
|
||||
loopRequired: o.loopRequired ?? MAX_EXPRESSION,
|
||||
loopEnum: o.loopEnum ?? MAX_EXPRESSION,
|
||||
meta: o.meta ?? true,
|
||||
messages: o.messages ?? true,
|
||||
inlineRefs: o.inlineRefs ?? true,
|
||||
schemaId: o.schemaId ?? "$id",
|
||||
addUsedSchema: o.addUsedSchema ?? true,
|
||||
validateSchema: o.validateSchema ?? true,
|
||||
validateFormats: o.validateFormats ?? true,
|
||||
unicodeRegExp: o.unicodeRegExp ?? true,
|
||||
int32range: o.int32range ?? true,
|
||||
uriResolver: uriResolver,
|
||||
}
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
log(...args: unknown[]): unknown
|
||||
warn(...args: unknown[]): unknown
|
||||
error(...args: unknown[]): unknown
|
||||
}
|
||||
|
||||
export default 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} = Object.create(null)
|
||||
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
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
validate<N extends never, T extends SomeJTDSchemaType>(
|
||||
schema: T,
|
||||
data: unknown
|
||||
): data is JTDDataType<T>
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
||||
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
|
||||
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
|
||||
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
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ErrorsTextOptions {
|
||||
separator?: string
|
||||
dataVar?: string
|
||||
}
|
||||
|
||||
function checkOptions(
|
||||
this: Ajv,
|
||||
checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
|
||||
options: Options & RemovedOptions,
|
||||
msg: string,
|
||||
log: "warn" | "error" = "error"
|
||||
): void {
|
||||
for (const key in checkOpts) {
|
||||
const opt = key as keyof typeof checkOpts
|
||||
if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
|
||||
}
|
||||
}
|
||||
|
||||
function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
|
||||
keyRef = normalizeId(keyRef) // TODO tests fail without this line
|
||||
return this.schemas[keyRef] || this.refs[keyRef]
|
||||
}
|
||||
|
||||
function addInitialSchemas(this: Ajv): void {
|
||||
const optsSchemas = this.opts.schemas
|
||||
if (!optsSchemas) return
|
||||
if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
|
||||
else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
|
||||
}
|
||||
|
||||
function addInitialFormats(this: Ajv): void {
|
||||
for (const name in this.opts.formats) {
|
||||
const format = this.opts.formats[name]
|
||||
if (format) this.addFormat(name, format)
|
||||
}
|
||||
}
|
||||
|
||||
function addInitialKeywords(
|
||||
this: Ajv,
|
||||
defs: Vocabulary | {[K in string]?: KeywordDefinition}
|
||||
): void {
|
||||
if (Array.isArray(defs)) {
|
||||
this.addVocabulary(defs)
|
||||
return
|
||||
}
|
||||
this.logger.warn("keywords option as map is deprecated, pass array")
|
||||
for (const keyword in defs) {
|
||||
const def = defs[keyword] as KeywordDefinition
|
||||
if (!def.keyword) def.keyword = keyword
|
||||
this.addKeyword(def)
|
||||
}
|
||||
}
|
||||
|
||||
function getMetaSchemaOptions(this: Ajv): InstanceOptions {
|
||||
const metaOpts = {...this.opts}
|
||||
for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
|
||||
return metaOpts
|
||||
}
|
||||
|
||||
const noLogs = {log() {}, warn() {}, error() {}}
|
||||
|
||||
function getLogger(logger?: Partial<Logger> | false): Logger {
|
||||
if (logger === false) return noLogs
|
||||
if (logger === undefined) return console
|
||||
if (logger.log && logger.warn && logger.error) return logger as Logger
|
||||
throw new Error("logger must implement log, warn and error methods")
|
||||
}
|
||||
|
||||
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i
|
||||
|
||||
function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
|
||||
const {RULES} = this
|
||||
eachItem(keyword, (kwd) => {
|
||||
if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
|
||||
if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
|
||||
})
|
||||
if (!def) return
|
||||
if (def.$data && !("code" in def || "validate" in def)) {
|
||||
throw new Error('$data keyword must have "code" or "validate" function')
|
||||
}
|
||||
}
|
||||
|
||||
function addRule(
|
||||
this: Ajv,
|
||||
keyword: string,
|
||||
definition?: AddedKeywordDefinition,
|
||||
dataType?: JSONType
|
||||
): void {
|
||||
const post = definition?.post
|
||||
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
|
||||
const {RULES} = this
|
||||
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
|
||||
if (!ruleGroup) {
|
||||
ruleGroup = {type: dataType, rules: []}
|
||||
RULES.rules.push(ruleGroup)
|
||||
}
|
||||
RULES.keywords[keyword] = true
|
||||
if (!definition) return
|
||||
|
||||
const rule: Rule = {
|
||||
keyword,
|
||||
definition: {
|
||||
...definition,
|
||||
type: getJSONTypes(definition.type),
|
||||
schemaType: getJSONTypes(definition.schemaType),
|
||||
},
|
||||
}
|
||||
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
|
||||
else ruleGroup.rules.push(rule)
|
||||
RULES.all[keyword] = rule
|
||||
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
|
||||
}
|
||||
|
||||
function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
|
||||
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
|
||||
if (i >= 0) {
|
||||
ruleGroup.rules.splice(i, 0, rule)
|
||||
} else {
|
||||
ruleGroup.rules.push(rule)
|
||||
this.logger.warn(`rule ${before} is not defined`)
|
||||
}
|
||||
}
|
||||
|
||||
function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
|
||||
let {metaSchema} = def
|
||||
if (metaSchema === undefined) return
|
||||
if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
|
||||
def.validateSchema = this.compile(metaSchema, true)
|
||||
}
|
||||
|
||||
const $dataRef = {
|
||||
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
}
|
||||
|
||||
function schemaOrData(schema: AnySchema): AnySchemaObject {
|
||||
return {anyOf: [schema, $dataRef]}
|
||||
}
|
||||
49
electron/node_modules/ajv/lib/data.js
generated
vendored
49
electron/node_modules/ajv/lib/data.js
generated
vendored
|
|
@ -1,49 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var KEYWORDS = [
|
||||
'multipleOf',
|
||||
'maximum',
|
||||
'exclusiveMaximum',
|
||||
'minimum',
|
||||
'exclusiveMinimum',
|
||||
'maxLength',
|
||||
'minLength',
|
||||
'pattern',
|
||||
'additionalItems',
|
||||
'maxItems',
|
||||
'minItems',
|
||||
'uniqueItems',
|
||||
'maxProperties',
|
||||
'minProperties',
|
||||
'required',
|
||||
'additionalProperties',
|
||||
'enum',
|
||||
'format',
|
||||
'const'
|
||||
];
|
||||
|
||||
module.exports = function (metaSchema, keywordsJsonPointers) {
|
||||
for (var i=0; i<keywordsJsonPointers.length; i++) {
|
||||
metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
||||
var segments = keywordsJsonPointers[i].split('/');
|
||||
var keywords = metaSchema;
|
||||
var j;
|
||||
for (j=1; j<segments.length; j++)
|
||||
keywords = keywords[segments[j]];
|
||||
|
||||
for (j=0; j<KEYWORDS.length; j++) {
|
||||
var key = KEYWORDS[j];
|
||||
var schema = keywords[key];
|
||||
if (schema) {
|
||||
keywords[key] = {
|
||||
anyOf: [
|
||||
schema,
|
||||
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return metaSchema;
|
||||
};
|
||||
37
electron/node_modules/ajv/lib/definition_schema.js
generated
vendored
37
electron/node_modules/ajv/lib/definition_schema.js
generated
vendored
|
|
@ -1,37 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
|
||||
module.exports = {
|
||||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
|
||||
definitions: {
|
||||
simpleTypes: metaSchema.definitions.simpleTypes
|
||||
},
|
||||
type: 'object',
|
||||
dependencies: {
|
||||
schema: ['validate'],
|
||||
$data: ['validate'],
|
||||
statements: ['inline'],
|
||||
valid: {not: {required: ['macro']}}
|
||||
},
|
||||
properties: {
|
||||
type: metaSchema.properties.type,
|
||||
schema: {type: 'boolean'},
|
||||
statements: {type: 'boolean'},
|
||||
dependencies: {
|
||||
type: 'array',
|
||||
items: {type: 'string'}
|
||||
},
|
||||
metaSchema: {type: 'object'},
|
||||
modifying: {type: 'boolean'},
|
||||
valid: {type: 'boolean'},
|
||||
$data: {type: 'boolean'},
|
||||
async: {type: 'boolean'},
|
||||
errors: {
|
||||
anyOf: [
|
||||
{type: 'boolean'},
|
||||
{const: 'full'}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
113
electron/node_modules/ajv/lib/dot/_limit.jst
generated
vendored
113
electron/node_modules/ajv/lib/dot/_limit.jst
generated
vendored
|
|
@ -1,113 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{## def.setExclusiveLimit:
|
||||
$exclusive = true;
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $isMax = $keyword == 'maximum'
|
||||
, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum'
|
||||
, $schemaExcl = it.schema[$exclusiveKeyword]
|
||||
, $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data
|
||||
, $op = $isMax ? '<' : '>'
|
||||
, $notOp = $isMax ? '>' : '<'
|
||||
, $errorKeyword = undefined;
|
||||
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined
|
||||
|| typeof $schemaExcl == 'number'
|
||||
|| typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
}}
|
||||
|
||||
{{? $isDataExcl }}
|
||||
{{
|
||||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr)
|
||||
, $exclusive = 'exclusive' + $lvl
|
||||
, $exclType = 'exclType' + $lvl
|
||||
, $exclIsNumber = 'exclIsNumber' + $lvl
|
||||
, $opExpr = 'op' + $lvl
|
||||
, $opStr = '\' + ' + $opExpr + ' + \'';
|
||||
}}
|
||||
var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}};
|
||||
{{ $schemaValueExcl = 'schemaExcl' + $lvl; }}
|
||||
|
||||
var {{=$exclusive}};
|
||||
var {{=$exclType}} = typeof {{=$schemaValueExcl}};
|
||||
if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') {
|
||||
{{ var $errorKeyword = $exclusiveKeyword; }}
|
||||
{{# def.error:'_exclusiveLimit' }}
|
||||
} else if ({{# def.$dataNotType:'number' }}
|
||||
{{=$exclType}} == 'number'
|
||||
? (
|
||||
({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}})
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
)
|
||||
: (
|
||||
({{=$exclusive}} = {{=$schemaValueExcl}} === true)
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaValue}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
)
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
|
||||
{{
|
||||
if ($schema === undefined) {
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
$schemaValue = $schemaValueExcl;
|
||||
$isData = $isDataExcl;
|
||||
}
|
||||
}}
|
||||
{{??}}
|
||||
{{
|
||||
var $exclIsNumber = typeof $schemaExcl == 'number'
|
||||
, $opStr = $op; /*used in error*/
|
||||
}}
|
||||
|
||||
{{? $exclIsNumber && $isData }}
|
||||
{{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }}
|
||||
if ({{# def.$dataNotType:'number' }}
|
||||
( {{=$schemaValue}} === undefined
|
||||
|| {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}}
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaExcl}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}} )
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
{{??}}
|
||||
{{
|
||||
if ($exclIsNumber && $schema === undefined) {
|
||||
{{# def.setExclusiveLimit }}
|
||||
$schemaValue = $schemaExcl;
|
||||
$notOp += '=';
|
||||
} else {
|
||||
if ($exclIsNumber)
|
||||
$schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
|
||||
|
||||
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
|
||||
{{# def.setExclusiveLimit }}
|
||||
$notOp += '=';
|
||||
} else {
|
||||
$exclusive = false;
|
||||
$opStr += '=';
|
||||
}
|
||||
}
|
||||
|
||||
var $opExpr = '\'' + $opStr + '\''; /*used in error*/
|
||||
}}
|
||||
|
||||
if ({{# def.$dataNotType:'number' }}
|
||||
{{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{ $errorKeyword = $errorKeyword || $keyword; }}
|
||||
{{# def.error:'_limit' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
12
electron/node_modules/ajv/lib/dot/_limitItems.jst
generated
vendored
12
electron/node_modules/ajv/lib/dot/_limitItems.jst
generated
vendored
|
|
@ -1,12 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitItems' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
12
electron/node_modules/ajv/lib/dot/_limitLength.jst
generated
vendored
12
electron/node_modules/ajv/lib/dot/_limitLength.jst
generated
vendored
|
|
@ -1,12 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitLength' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
12
electron/node_modules/ajv/lib/dot/_limitProperties.jst
generated
vendored
12
electron/node_modules/ajv/lib/dot/_limitProperties.jst
generated
vendored
|
|
@ -1,12 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitProperties' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
32
electron/node_modules/ajv/lib/dot/allOf.jst
generated
vendored
32
electron/node_modules/ajv/lib/dot/allOf.jst
generated
vendored
|
|
@ -1,32 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{
|
||||
var $currentBaseId = $it.baseId
|
||||
, $allSchemasEmpty = true;
|
||||
}}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{
|
||||
$allSchemasEmpty = false;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{? $allSchemasEmpty }}
|
||||
if (true) {
|
||||
{{??}}
|
||||
{{= $closingBraces.slice(0,-1) }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
46
electron/node_modules/ajv/lib/dot/anyOf.jst
generated
vendored
46
electron/node_modules/ajv/lib/dot/anyOf.jst
generated
vendored
|
|
@ -1,46 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{
|
||||
var $noEmptySchema = $schema.every(function($sch) {
|
||||
return {{# def.nonEmptySchema:$sch }};
|
||||
});
|
||||
}}
|
||||
{{? $noEmptySchema }}
|
||||
{{ var $currentBaseId = $it.baseId; }}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}} = false;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
|
||||
{{=$valid}} = {{=$valid}} || {{=$nextValid}};
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{~}}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
{{= $closingBraces }}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.extraError:'anyOf' }}
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
51
electron/node_modules/ajv/lib/dot/coerce.def
generated
vendored
51
electron/node_modules/ajv/lib/dot/coerce.def
generated
vendored
|
|
@ -1,51 +0,0 @@
|
|||
{{## def.coerceType:
|
||||
{{
|
||||
var $dataType = 'dataType' + $lvl
|
||||
, $coerced = 'coerced' + $lvl;
|
||||
}}
|
||||
var {{=$dataType}} = typeof {{=$data}};
|
||||
var {{=$coerced}} = undefined;
|
||||
|
||||
{{? it.opts.coerceTypes == 'array' }}
|
||||
if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) {
|
||||
{{=$data}} = {{=$data}}[0];
|
||||
{{=$dataType}} = typeof {{=$data}};
|
||||
if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}};
|
||||
}
|
||||
{{?}}
|
||||
|
||||
if ({{=$coerced}} !== undefined) ;
|
||||
{{~ $coerceToTypes:$type:$i }}
|
||||
{{? $type == 'string' }}
|
||||
else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean')
|
||||
{{=$coerced}} = '' + {{=$data}};
|
||||
else if ({{=$data}} === null) {{=$coerced}} = '';
|
||||
{{?? $type == 'number' || $type == 'integer' }}
|
||||
else if ({{=$dataType}} == 'boolean' || {{=$data}} === null
|
||||
|| ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}}
|
||||
{{? $type == 'integer' }} && !({{=$data}} % 1){{?}}))
|
||||
{{=$coerced}} = +{{=$data}};
|
||||
{{?? $type == 'boolean' }}
|
||||
else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null)
|
||||
{{=$coerced}} = false;
|
||||
else if ({{=$data}} === 'true' || {{=$data}} === 1)
|
||||
{{=$coerced}} = true;
|
||||
{{?? $type == 'null' }}
|
||||
else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false)
|
||||
{{=$coerced}} = null;
|
||||
{{?? it.opts.coerceTypes == 'array' && $type == 'array' }}
|
||||
else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null)
|
||||
{{=$coerced}} = [{{=$data}}];
|
||||
{{?}}
|
||||
{{~}}
|
||||
else {
|
||||
{{# def.error:'type' }}
|
||||
}
|
||||
|
||||
if ({{=$coerced}} !== undefined) {
|
||||
{{# def.setParentData }}
|
||||
{{=$data}} = {{=$coerced}};
|
||||
{{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}}
|
||||
{{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}};
|
||||
}
|
||||
#}}
|
||||
9
electron/node_modules/ajv/lib/dot/comment.jst
generated
vendored
9
electron/node_modules/ajv/lib/dot/comment.jst
generated
vendored
|
|
@ -1,9 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.setupKeyword }}
|
||||
|
||||
{{ var $comment = it.util.toQuotedString($schema); }}
|
||||
{{? it.opts.$comment === true }}
|
||||
console.log({{=$comment}});
|
||||
{{?? typeof it.opts.$comment == 'function' }}
|
||||
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
|
||||
{{?}}
|
||||
11
electron/node_modules/ajv/lib/dot/const.jst
generated
vendored
11
electron/node_modules/ajv/lib/dot/const.jst
generated
vendored
|
|
@ -1,11 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{? !$isData }}
|
||||
var schema{{=$lvl}} = validate.schema{{=$schemaPath}};
|
||||
{{?}}
|
||||
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}});
|
||||
{{# def.checkError:'const' }}
|
||||
{{? $breakOnError }} else { {{?}}
|
||||
55
electron/node_modules/ajv/lib/dot/contains.jst
generated
vendored
55
electron/node_modules/ajv/lib/dot/contains.jst
generated
vendored
|
|
@ -1,55 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{
|
||||
var $idx = 'i' + $lvl
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $currentBaseId = it.baseId
|
||||
, $nonEmptySchema = {{# def.nonEmptySchema:$schema }};
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{? $nonEmptySchema }}
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
|
||||
var {{=$nextValid}} = false;
|
||||
|
||||
for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
|
||||
{{
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
|
||||
if ({{=$nextValid}}) break;
|
||||
}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
{{= $closingBraces }}
|
||||
|
||||
if (!{{=$nextValid}}) {
|
||||
{{??}}
|
||||
if ({{=$data}}.length == 0) {
|
||||
{{?}}
|
||||
|
||||
{{# def.error:'contains' }}
|
||||
} else {
|
||||
{{? $nonEmptySchema }}
|
||||
{{# def.resetErrors }}
|
||||
{{?}}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
191
electron/node_modules/ajv/lib/dot/custom.jst
generated
vendored
191
electron/node_modules/ajv/lib/dot/custom.jst
generated
vendored
|
|
@ -1,191 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{
|
||||
var $rule = this
|
||||
, $definition = 'definition' + $lvl
|
||||
, $rDef = $rule.definition
|
||||
, $closingBraces = '';
|
||||
var $validate = $rDef.validate;
|
||||
var $compile, $inline, $macro, $ruleValidate, $validateCode;
|
||||
}}
|
||||
|
||||
{{? $isData && $rDef.$data }}
|
||||
{{
|
||||
$validateCode = 'keywordValidate' + $lvl;
|
||||
var $validateSchema = $rDef.validateSchema;
|
||||
}}
|
||||
var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition;
|
||||
var {{=$validateCode}} = {{=$definition}}.validate;
|
||||
{{??}}
|
||||
{{
|
||||
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
|
||||
if (!$ruleValidate) return;
|
||||
$schemaValue = 'validate.schema' + $schemaPath;
|
||||
$validateCode = $ruleValidate.code;
|
||||
$compile = $rDef.compile;
|
||||
$inline = $rDef.inline;
|
||||
$macro = $rDef.macro;
|
||||
}}
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
var $ruleErrs = $validateCode + '.errors'
|
||||
, $i = 'i' + $lvl
|
||||
, $ruleErr = 'ruleErr' + $lvl
|
||||
, $asyncKeyword = $rDef.async;
|
||||
|
||||
if ($asyncKeyword && !it.async)
|
||||
throw new Error('async keyword in sync schema');
|
||||
}}
|
||||
|
||||
|
||||
{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{## def.callRuleValidate:
|
||||
{{=$validateCode}}.call(
|
||||
{{? it.opts.passContext }}this{{??}}self{{?}}
|
||||
{{? $compile || $rDef.schema === false }}
|
||||
, {{=$data}}
|
||||
{{??}}
|
||||
, {{=$schemaValue}}
|
||||
, {{=$data}}
|
||||
, validate.schema{{=it.schemaPath}}
|
||||
{{?}}
|
||||
, {{# def.dataPath }}
|
||||
{{# def.passParentData }}
|
||||
, rootData
|
||||
)
|
||||
#}}
|
||||
|
||||
{{## def.extendErrors:_inline:
|
||||
for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) {
|
||||
var {{=$ruleErr}} = vErrors[{{=$i}}];
|
||||
if ({{=$ruleErr}}.dataPath === undefined)
|
||||
{{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }};
|
||||
{{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }}
|
||||
{{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}";
|
||||
{{# _inline ? '}' : '' }}
|
||||
{{? it.opts.verbose }}
|
||||
{{=$ruleErr}}.schema = {{=$schemaValue}};
|
||||
{{=$ruleErr}}.data = {{=$data}};
|
||||
{{?}}
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{? $isData && $rDef.$data }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
if ({{=$schemaValue}} === undefined) {
|
||||
{{=$valid}} = true;
|
||||
} else {
|
||||
{{? $validateSchema }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}});
|
||||
if ({{=$valid}}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $inline }}
|
||||
{{? $rDef.statements }}
|
||||
{{= $ruleValidate.validate }}
|
||||
{{??}}
|
||||
{{=$valid}} = {{= $ruleValidate.validate }};
|
||||
{{?}}
|
||||
{{?? $macro }}
|
||||
{{# def.setupNextLevel }}
|
||||
{{
|
||||
$it.schema = $ruleValidate.validate;
|
||||
$it.schemaPath = '';
|
||||
}}
|
||||
{{# def.setCompositeRule }}
|
||||
{{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }}
|
||||
{{# def.resetCompositeRule }}
|
||||
{{= $code }}
|
||||
{{??}}
|
||||
{{# def.beginDefOut}}
|
||||
{{# def.callRuleValidate }}
|
||||
{{# def.storeDefOut:def_callRuleValidate }}
|
||||
|
||||
{{? $rDef.errors === false }}
|
||||
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
|
||||
{{??}}
|
||||
{{? $asyncKeyword }}
|
||||
{{ $ruleErrs = 'customErrors' + $lvl; }}
|
||||
var {{=$ruleErrs}} = null;
|
||||
try {
|
||||
{{=$valid}} = await {{= def_callRuleValidate }};
|
||||
} catch (e) {
|
||||
{{=$valid}} = false;
|
||||
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;
|
||||
else throw e;
|
||||
}
|
||||
{{??}}
|
||||
{{=$ruleErrs}} = null;
|
||||
{{=$valid}} = {{= def_callRuleValidate }};
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $rDef.modifying }}
|
||||
if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}];
|
||||
{{?}}
|
||||
|
||||
{{= $closingBraces }}
|
||||
|
||||
{{## def.notValidationResult:
|
||||
{{? $rDef.valid === undefined }}
|
||||
!{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}}
|
||||
{{??}}
|
||||
{{= !$rDef.valid }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
{{? $rDef.valid }}
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{??}}
|
||||
if ({{# def.notValidationResult }}) {
|
||||
{{ $errorKeyword = $rule.keyword; }}
|
||||
{{# def.beginDefOut}}
|
||||
{{# def.error:'custom' }}
|
||||
{{# def.storeDefOut:def_customError }}
|
||||
|
||||
{{? $inline }}
|
||||
{{? $rDef.errors }}
|
||||
{{? $rDef.errors != 'full' }}
|
||||
{{# def.extendErrors:true }}
|
||||
{{?}}
|
||||
{{??}}
|
||||
{{? $rDef.errors === false}}
|
||||
{{= def_customError }}
|
||||
{{??}}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{= def_customError }}
|
||||
} else {
|
||||
{{# def.extendErrors:true }}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{?? $macro }}
|
||||
{{# def.extraError:'custom' }}
|
||||
{{??}}
|
||||
{{? $rDef.errors === false}}
|
||||
{{= def_customError }}
|
||||
{{??}}
|
||||
if (Array.isArray({{=$ruleErrs}})) {
|
||||
if (vErrors === null) vErrors = {{=$ruleErrs}};
|
||||
else vErrors = vErrors.concat({{=$ruleErrs}});
|
||||
errors = vErrors.length;
|
||||
{{# def.extendErrors:false }}
|
||||
} else {
|
||||
{{= def_customError }}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
{{?}}
|
||||
47
electron/node_modules/ajv/lib/dot/defaults.def
generated
vendored
47
electron/node_modules/ajv/lib/dot/defaults.def
generated
vendored
|
|
@ -1,47 +0,0 @@
|
|||
{{## def.assignDefault:
|
||||
{{? it.compositeRule }}
|
||||
{{
|
||||
if (it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored for: ' + $passData;
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
}}
|
||||
{{??}}
|
||||
if ({{=$passData}} === undefined
|
||||
{{? it.opts.useDefaults == 'empty' }}
|
||||
|| {{=$passData}} === null
|
||||
|| {{=$passData}} === ''
|
||||
{{?}}
|
||||
)
|
||||
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
|
||||
{{= it.useDefault($sch.default) }}
|
||||
{{??}}
|
||||
{{= JSON.stringify($sch.default) }}
|
||||
{{?}};
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.defaultProperties:
|
||||
{{
|
||||
var $schema = it.schema.properties
|
||||
, $schemaKeys = Object.keys($schema); }}
|
||||
{{~ $schemaKeys:$propertyKey }}
|
||||
{{ var $sch = $schema[$propertyKey]; }}
|
||||
{{? $sch.default !== undefined }}
|
||||
{{ var $passData = $data + it.util.getProperty($propertyKey); }}
|
||||
{{# def.assignDefault }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.defaultItems:
|
||||
{{~ it.schema.items:$sch:$i }}
|
||||
{{? $sch.default !== undefined }}
|
||||
{{ var $passData = $data + '[' + $i + ']'; }}
|
||||
{{# def.assignDefault }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
#}}
|
||||
203
electron/node_modules/ajv/lib/dot/definitions.def
generated
vendored
203
electron/node_modules/ajv/lib/dot/definitions.def
generated
vendored
|
|
@ -1,203 +0,0 @@
|
|||
{{## def.setupKeyword:
|
||||
{{
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.setCompositeRule:
|
||||
{{
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.resetCompositeRule:
|
||||
{{ it.compositeRule = $it.compositeRule = $wasComposite; }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.setupNextLevel:
|
||||
{{
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.ifValid:
|
||||
{{? $breakOnError }}
|
||||
if ({{=$valid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.ifResultValid:
|
||||
{{? $breakOnError }}
|
||||
if ({{=$nextValid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.elseIfValid:
|
||||
{{? $breakOnError }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
else {
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.nonEmptySchema:_schema:
|
||||
(it.opts.strictKeywords
|
||||
? (typeof _schema == 'object' && Object.keys(_schema).length > 0)
|
||||
|| _schema === false
|
||||
: it.util.schemaHasRules(_schema, it.RULES.all))
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.strLength:
|
||||
{{? it.opts.unicode === false }}
|
||||
{{=$data}}.length
|
||||
{{??}}
|
||||
ucs2length({{=$data}})
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.willOptimize:
|
||||
it.util.varOccurences($code, $nextData) < 2
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.generateSubschemaCode:
|
||||
{{
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.insertSubschemaCode:
|
||||
{{= it.validate($it) }}
|
||||
{{ $it.baseId = $currentBaseId; }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def._optimizeValidate:
|
||||
it.util.varReplace($code, $nextData, $passData)
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.optimizeValidate:
|
||||
{{? {{# def.willOptimize}} }}
|
||||
{{= {{# def._optimizeValidate }} }}
|
||||
{{??}}
|
||||
var {{=$nextData}} = {{=$passData}};
|
||||
{{= $code }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.$data:
|
||||
{{
|
||||
var $isData = it.opts.$data && $schema && $schema.$data
|
||||
, $schemaValue;
|
||||
}}
|
||||
{{? $isData }}
|
||||
var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }};
|
||||
{{ $schemaValue = 'schema' + $lvl; }}
|
||||
{{??}}
|
||||
{{ $schemaValue = $schema; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.$dataNotType:_type:
|
||||
{{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.check$dataIsArray:
|
||||
if (schema{{=$lvl}} === undefined) {{=$valid}} = true;
|
||||
else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false;
|
||||
else {
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.numberKeyword:
|
||||
{{? !($isData || typeof $schema == 'number') }}
|
||||
{{ throw new Error($keyword + ' must be number'); }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.beginDefOut:
|
||||
{{
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = '';
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.storeDefOut:_variable:
|
||||
{{
|
||||
var _variable = out;
|
||||
out = $$outStack.pop();
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}}
|
||||
|
||||
{{## def.setParentData:
|
||||
{{
|
||||
var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData'
|
||||
, $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
|
||||
}}
|
||||
#}}
|
||||
|
||||
{{## def.passParentData:
|
||||
{{# def.setParentData }}
|
||||
, {{= $parentData }}
|
||||
, {{= $parentDataProperty }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.iterateProperties:
|
||||
{{? $ownProperties }}
|
||||
{{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}});
|
||||
for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) {
|
||||
var {{=$key}} = {{=$dataProperties}}[{{=$idx}}];
|
||||
{{??}}
|
||||
for (var {{=$key}} in {{=$data}}) {
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.noPropertyInData:
|
||||
{{=$useData}} === undefined
|
||||
{{? $ownProperties }}
|
||||
|| !{{# def.isOwnProperty }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.isOwnProperty:
|
||||
Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}')
|
||||
#}}
|
||||
79
electron/node_modules/ajv/lib/dot/dependencies.jst
generated
vendored
79
electron/node_modules/ajv/lib/dot/dependencies.jst
generated
vendored
|
|
@ -1,79 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.missing }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.propertyInData:
|
||||
{{=$data}}{{= it.util.getProperty($property) }} !== undefined
|
||||
{{? $ownProperties }}
|
||||
&& Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}')
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{
|
||||
var $schemaDeps = {}
|
||||
, $propertyDeps = {}
|
||||
, $ownProperties = it.opts.ownProperties;
|
||||
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
}
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
|
||||
{{ var $currentErrorPath = it.errorPath; }}
|
||||
|
||||
var missing{{=$lvl}};
|
||||
{{ for (var $property in $propertyDeps) { }}
|
||||
{{ $deps = $propertyDeps[$property]; }}
|
||||
{{? $deps.length }}
|
||||
if ({{# def.propertyInData }}
|
||||
{{? $breakOnError }}
|
||||
&& ({{# def.checkMissingProperty:$deps }})) {
|
||||
{{# def.errorMissingProperty:'dependencies' }}
|
||||
{{??}}
|
||||
) {
|
||||
{{~ $deps:$propertyKey }}
|
||||
{{# def.allErrorsMissingProperty:'dependencies' }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
} {{# def.elseIfValid }}
|
||||
{{?}}
|
||||
{{ } }}
|
||||
|
||||
{{
|
||||
it.errorPath = $currentErrorPath;
|
||||
var $currentBaseId = $it.baseId;
|
||||
}}
|
||||
|
||||
|
||||
{{ for (var $property in $schemaDeps) { }}
|
||||
{{ var $sch = $schemaDeps[$property]; }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{# def.propertyInData }}) {
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + it.util.getProperty($property);
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{ } }}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
30
electron/node_modules/ajv/lib/dot/enum.jst
generated
vendored
30
electron/node_modules/ajv/lib/dot/enum.jst
generated
vendored
|
|
@ -1,30 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{
|
||||
var $i = 'i' + $lvl
|
||||
, $vSchema = 'schema' + $lvl;
|
||||
}}
|
||||
|
||||
{{? !$isData }}
|
||||
var {{=$vSchema}} = validate.schema{{=$schemaPath}};
|
||||
{{?}}
|
||||
var {{=$valid}};
|
||||
|
||||
{{?$isData}}{{# def.check$dataIsArray }}{{?}}
|
||||
|
||||
{{=$valid}} = false;
|
||||
|
||||
for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++)
|
||||
if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) {
|
||||
{{=$valid}} = true;
|
||||
break;
|
||||
}
|
||||
|
||||
{{? $isData }} } {{?}}
|
||||
|
||||
{{# def.checkError:'enum' }}
|
||||
|
||||
{{? $breakOnError }} else { {{?}}
|
||||
194
electron/node_modules/ajv/lib/dot/errors.def
generated
vendored
194
electron/node_modules/ajv/lib/dot/errors.def
generated
vendored
|
|
@ -1,194 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
|
||||
{{## def._error:_rule:
|
||||
{{ 'istanbul ignore else'; }}
|
||||
{{? it.createErrors !== false }}
|
||||
{
|
||||
keyword: '{{= $errorKeyword || _rule }}'
|
||||
, dataPath: (dataPath || '') + {{= it.errorPath }}
|
||||
, schemaPath: {{=it.util.toQuotedString($errSchemaPath)}}
|
||||
, params: {{# def._errorParams[_rule] }}
|
||||
{{? it.opts.messages !== false }}
|
||||
, message: {{# def._errorMessages[_rule] }}
|
||||
{{?}}
|
||||
{{? it.opts.verbose }}
|
||||
, schema: {{# def._errorSchemas[_rule] }}
|
||||
, parentSchema: validate.schema{{=it.schemaPath}}
|
||||
, data: {{=$data}}
|
||||
{{?}}
|
||||
}
|
||||
{{??}}
|
||||
{}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def._addError:_rule:
|
||||
if (vErrors === null) vErrors = [err];
|
||||
else vErrors.push(err);
|
||||
errors++;
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.addError:_rule:
|
||||
var err = {{# def._error:_rule }};
|
||||
{{# def._addError:_rule }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.error:_rule:
|
||||
{{# def.beginDefOut}}
|
||||
{{# def._error:_rule }}
|
||||
{{# def.storeDefOut:__err }}
|
||||
|
||||
{{? !it.compositeRule && $breakOnError }}
|
||||
{{ 'istanbul ignore if'; }}
|
||||
{{? it.async }}
|
||||
throw new ValidationError([{{=__err}}]);
|
||||
{{??}}
|
||||
validate.errors = [{{=__err}}];
|
||||
return false;
|
||||
{{?}}
|
||||
{{??}}
|
||||
var err = {{=__err}};
|
||||
{{# def._addError:_rule }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.extraError:_rule:
|
||||
{{# def.addError:_rule}}
|
||||
{{? !it.compositeRule && $breakOnError }}
|
||||
{{ 'istanbul ignore if'; }}
|
||||
{{? it.async }}
|
||||
throw new ValidationError(vErrors);
|
||||
{{??}}
|
||||
validate.errors = vErrors;
|
||||
return false;
|
||||
{{?}}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.checkError:_rule:
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.error:_rule }}
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.resetErrors:
|
||||
errors = {{=$errs}};
|
||||
if (vErrors !== null) {
|
||||
if ({{=$errs}}) vErrors.length = {{=$errs}};
|
||||
else vErrors = null;
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}}
|
||||
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}}
|
||||
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}}
|
||||
|
||||
{{## def._errorMessages = {
|
||||
'false schema': "'boolean schema is false'",
|
||||
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
|
||||
additionalItems: "'should NOT have more than {{=$schema.length}} items'",
|
||||
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
|
||||
anyOf: "'should match some schema in anyOf'",
|
||||
const: "'should be equal to constant'",
|
||||
contains: "'should contain a valid item'",
|
||||
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
|
||||
'enum': "'should be equal to one of the allowed values'",
|
||||
format: "'should match format \"{{#def.concatSchemaEQ}}\"'",
|
||||
'if': "'should match \"' + {{=$ifClause}} + '\" schema'",
|
||||
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}",
|
||||
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
|
||||
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
|
||||
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
|
||||
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
|
||||
multipleOf: "'should be multiple of {{#def.appendSchema}}",
|
||||
not: "'should NOT be valid'",
|
||||
oneOf: "'should match exactly one schema in oneOf'",
|
||||
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
|
||||
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'",
|
||||
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
|
||||
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
|
||||
uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'",
|
||||
custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'",
|
||||
patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''",
|
||||
switch: "'should pass \"switch\" keyword validation'",
|
||||
_formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'",
|
||||
_formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'"
|
||||
} #}}
|
||||
|
||||
|
||||
{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}}
|
||||
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
|
||||
|
||||
{{## def._errorSchemas = {
|
||||
'false schema': "false",
|
||||
$ref: "{{=it.util.toQuotedString($schema)}}",
|
||||
additionalItems: "false",
|
||||
additionalProperties: "false",
|
||||
anyOf: "validate.schema{{=$schemaPath}}",
|
||||
const: "validate.schema{{=$schemaPath}}",
|
||||
contains: "validate.schema{{=$schemaPath}}",
|
||||
dependencies: "validate.schema{{=$schemaPath}}",
|
||||
'enum': "validate.schema{{=$schemaPath}}",
|
||||
format: "{{#def.schemaRefOrQS}}",
|
||||
'if': "validate.schema{{=$schemaPath}}",
|
||||
_limit: "{{#def.schemaRefOrVal}}",
|
||||
_exclusiveLimit: "validate.schema{{=$schemaPath}}",
|
||||
_limitItems: "{{#def.schemaRefOrVal}}",
|
||||
_limitLength: "{{#def.schemaRefOrVal}}",
|
||||
_limitProperties:"{{#def.schemaRefOrVal}}",
|
||||
multipleOf: "{{#def.schemaRefOrVal}}",
|
||||
not: "validate.schema{{=$schemaPath}}",
|
||||
oneOf: "validate.schema{{=$schemaPath}}",
|
||||
pattern: "{{#def.schemaRefOrQS}}",
|
||||
propertyNames: "validate.schema{{=$schemaPath}}",
|
||||
required: "validate.schema{{=$schemaPath}}",
|
||||
type: "validate.schema{{=$schemaPath}}",
|
||||
uniqueItems: "{{#def.schemaRefOrVal}}",
|
||||
custom: "validate.schema{{=$schemaPath}}",
|
||||
patternRequired: "validate.schema{{=$schemaPath}}",
|
||||
switch: "validate.schema{{=$schemaPath}}",
|
||||
_formatLimit: "{{#def.schemaRefOrQS}}",
|
||||
_formatExclusiveLimit: "validate.schema{{=$schemaPath}}"
|
||||
} #}}
|
||||
|
||||
|
||||
{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
|
||||
|
||||
{{## def._errorParams = {
|
||||
'false schema': "{}",
|
||||
$ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }",
|
||||
additionalItems: "{ limit: {{=$schema.length}} }",
|
||||
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
|
||||
anyOf: "{}",
|
||||
const: "{ allowedValue: schema{{=$lvl}} }",
|
||||
contains: "{}",
|
||||
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
|
||||
'enum': "{ allowedValues: schema{{=$lvl}} }",
|
||||
format: "{ format: {{#def.schemaValueQS}} }",
|
||||
'if': "{ failingKeyword: {{=$ifClause}} }",
|
||||
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
|
||||
_exclusiveLimit: "{}",
|
||||
_limitItems: "{ limit: {{=$schemaValue}} }",
|
||||
_limitLength: "{ limit: {{=$schemaValue}} }",
|
||||
_limitProperties:"{ limit: {{=$schemaValue}} }",
|
||||
multipleOf: "{ multipleOf: {{=$schemaValue}} }",
|
||||
not: "{}",
|
||||
oneOf: "{ passingSchemas: {{=$passingSchemas}} }",
|
||||
pattern: "{ pattern: {{#def.schemaValueQS}} }",
|
||||
propertyNames: "{ propertyName: '{{=$invalidName}}' }",
|
||||
required: "{ missingProperty: '{{=$missingProperty}}' }",
|
||||
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",
|
||||
uniqueItems: "{ i: i, j: j }",
|
||||
custom: "{ keyword: '{{=$rule.keyword}}' }",
|
||||
patternRequired: "{ missingPattern: '{{=$missingPattern}}' }",
|
||||
switch: "{ caseIndex: {{=$caseIndex}} }",
|
||||
_formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }",
|
||||
_formatExclusiveLimit: "{}"
|
||||
} #}}
|
||||
106
electron/node_modules/ajv/lib/dot/format.jst
generated
vendored
106
electron/node_modules/ajv/lib/dot/format.jst
generated
vendored
|
|
@ -1,106 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
|
||||
{{## def.skipFormat:
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{ return out; }}
|
||||
#}}
|
||||
|
||||
{{? it.opts.format === false }}{{# def.skipFormat }}{{?}}
|
||||
|
||||
|
||||
{{# def.$data }}
|
||||
|
||||
|
||||
{{## def.$dataCheckFormat:
|
||||
{{# def.$dataNotType:'string' }}
|
||||
({{? $unknownFormats != 'ignore' }}
|
||||
({{=$schemaValue}} && !{{=$format}}
|
||||
{{? $allowUnknown }}
|
||||
&& self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1
|
||||
{{?}}) ||
|
||||
{{?}}
|
||||
({{=$format}} && {{=$formatType}} == '{{=$ruleType}}'
|
||||
&& !(typeof {{=$format}} == 'function'
|
||||
? {{? it.async}}
|
||||
(async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
|
||||
{{??}}
|
||||
{{=$format}}({{=$data}})
|
||||
{{?}}
|
||||
: {{=$format}}.test({{=$data}}))))
|
||||
#}}
|
||||
|
||||
{{## def.checkFormat:
|
||||
{{
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema);
|
||||
if ($isObject) $formatRef += '.validate';
|
||||
}}
|
||||
{{? typeof $format == 'function' }}
|
||||
{{=$formatRef}}({{=$data}})
|
||||
{{??}}
|
||||
{{=$formatRef}}.test({{=$data}})
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{
|
||||
var $unknownFormats = it.opts.unknownFormats
|
||||
, $allowUnknown = Array.isArray($unknownFormats);
|
||||
}}
|
||||
|
||||
{{? $isData }}
|
||||
{{
|
||||
var $format = 'format' + $lvl
|
||||
, $isObject = 'isObject' + $lvl
|
||||
, $formatType = 'formatType' + $lvl;
|
||||
}}
|
||||
var {{=$format}} = formats[{{=$schemaValue}}];
|
||||
var {{=$isObject}} = typeof {{=$format}} == 'object'
|
||||
&& !({{=$format}} instanceof RegExp)
|
||||
&& {{=$format}}.validate;
|
||||
var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string';
|
||||
if ({{=$isObject}}) {
|
||||
{{? it.async}}
|
||||
var async{{=$lvl}} = {{=$format}}.async;
|
||||
{{?}}
|
||||
{{=$format}} = {{=$format}}.validate;
|
||||
}
|
||||
if ({{# def.$dataCheckFormat }}) {
|
||||
{{??}}
|
||||
{{ var $format = it.formats[$schema]; }}
|
||||
{{? !$format }}
|
||||
{{? $unknownFormats == 'ignore' }}
|
||||
{{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }}
|
||||
{{# def.skipFormat }}
|
||||
{{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }}
|
||||
{{# def.skipFormat }}
|
||||
{{??}}
|
||||
{{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{
|
||||
var $isObject = typeof $format == 'object'
|
||||
&& !($format instanceof RegExp)
|
||||
&& $format.validate;
|
||||
var $formatType = $isObject && $format.type || 'string';
|
||||
if ($isObject) {
|
||||
var $async = $format.async === true;
|
||||
$format = $format.validate;
|
||||
}
|
||||
}}
|
||||
{{? $formatType != $ruleType }}
|
||||
{{# def.skipFormat }}
|
||||
{{?}}
|
||||
{{? $async }}
|
||||
{{
|
||||
if (!it.async) throw new Error('async format in sync schema');
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
|
||||
}}
|
||||
if (!(await {{=$formatRef}}({{=$data}}))) {
|
||||
{{??}}
|
||||
if (!{{# def.checkFormat }}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{# def.error:'format' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
73
electron/node_modules/ajv/lib/dot/if.jst
generated
vendored
73
electron/node_modules/ajv/lib/dot/if.jst
generated
vendored
|
|
@ -1,73 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.validateIfClause:_clause:
|
||||
{{
|
||||
$it.schema = it.schema['_clause'];
|
||||
$it.schemaPath = it.schemaPath + '._clause';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/_clause';
|
||||
}}
|
||||
{{# def.insertSubschemaCode }}
|
||||
{{=$valid}} = {{=$nextValid}};
|
||||
{{? $thenPresent && $elsePresent }}
|
||||
{{ $ifClause = 'ifClause' + $lvl; }}
|
||||
var {{=$ifClause}} = '_clause';
|
||||
{{??}}
|
||||
{{ $ifClause = '\'_clause\''; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $thenSch = it.schema['then']
|
||||
, $elseSch = it.schema['else']
|
||||
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
|
||||
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
|
||||
, $currentBaseId = $it.baseId;
|
||||
}}
|
||||
|
||||
{{? $thenPresent || $elsePresent }}
|
||||
{{
|
||||
var $ifClause;
|
||||
$it.createErrors = false;
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}} = true;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
{{# def.insertSubschemaCode }}
|
||||
{{ $it.createErrors = true; }}
|
||||
{{# def.resetErrors }}
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
{{? $thenPresent }}
|
||||
if ({{=$nextValid}}) {
|
||||
{{# def.validateIfClause:then }}
|
||||
}
|
||||
{{? $elsePresent }}
|
||||
else {
|
||||
{{?}}
|
||||
{{??}}
|
||||
if (!{{=$nextValid}}) {
|
||||
{{?}}
|
||||
|
||||
{{? $elsePresent }}
|
||||
{{# def.validateIfClause:else }}
|
||||
}
|
||||
{{?}}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.extraError:'if' }}
|
||||
}
|
||||
{{? $breakOnError }} else { {{?}}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
98
electron/node_modules/ajv/lib/dot/items.jst
generated
vendored
98
electron/node_modules/ajv/lib/dot/items.jst
generated
vendored
|
|
@ -1,98 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.validateItems:startFrom:
|
||||
for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
|
||||
{{
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
|
||||
{{? $breakOnError }}
|
||||
if (!{{=$nextValid}}) break;
|
||||
{{?}}
|
||||
}
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $idx = 'i' + $lvl
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $currentBaseId = it.baseId;
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{? Array.isArray($schema) }}
|
||||
{{ /* 'items' is an array of schemas */}}
|
||||
{{ var $additionalItems = it.schema.additionalItems; }}
|
||||
{{? $additionalItems === false }}
|
||||
{{=$valid}} = {{=$data}}.length <= {{= $schema.length }};
|
||||
{{
|
||||
var $currErrSchemaPath = $errSchemaPath;
|
||||
$errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
}}
|
||||
{{# def.checkError:'additionalItems' }}
|
||||
{{ $errSchemaPath = $currErrSchemaPath; }}
|
||||
{{# def.elseIfValid}}
|
||||
{{?}}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{=$data}}.length > {{=$i}}) {
|
||||
{{
|
||||
var $passData = $data + '[' + $i + ']';
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
|
||||
$it.dataPathArr[$dataNxt] = $i;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
|
||||
{{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }}
|
||||
{{
|
||||
$it.schema = $additionalItems;
|
||||
$it.schemaPath = it.schemaPath + '.additionalItems';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
}}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{=$data}}.length > {{= $schema.length }}) {
|
||||
{{# def.validateItems: $schema.length }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
|
||||
{{?? {{# def.nonEmptySchema:$schema }} }}
|
||||
{{ /* 'items' is a single schema */}}
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
{{# def.validateItems: 0 }}
|
||||
{{?}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
39
electron/node_modules/ajv/lib/dot/missing.def
generated
vendored
39
electron/node_modules/ajv/lib/dot/missing.def
generated
vendored
|
|
@ -1,39 +0,0 @@
|
|||
{{## def.checkMissingProperty:_properties:
|
||||
{{~ _properties:$propertyKey:$i }}
|
||||
{{?$i}} || {{?}}
|
||||
{{
|
||||
var $prop = it.util.getProperty($propertyKey)
|
||||
, $useData = $data + $prop;
|
||||
}}
|
||||
( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) )
|
||||
{{~}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.errorMissingProperty:_error:
|
||||
{{
|
||||
var $propertyPath = 'missing' + $lvl
|
||||
, $missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.opts.jsonPointers
|
||||
? it.util.getPathExpr($currentErrorPath, $propertyPath, true)
|
||||
: $currentErrorPath + ' + ' + $propertyPath;
|
||||
}
|
||||
}}
|
||||
{{# def.error:_error }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.allErrorsMissingProperty:_error:
|
||||
{{
|
||||
var $prop = it.util.getProperty($propertyKey)
|
||||
, $missingProperty = it.util.escapeQuotes($propertyKey)
|
||||
, $useData = $data + $prop;
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
}}
|
||||
if ({{# def.noPropertyInData }}) {
|
||||
{{# def.addError:_error }}
|
||||
}
|
||||
#}}
|
||||
22
electron/node_modules/ajv/lib/dot/multipleOf.jst
generated
vendored
22
electron/node_modules/ajv/lib/dot/multipleOf.jst
generated
vendored
|
|
@ -1,22 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
var division{{=$lvl}};
|
||||
if ({{?$isData}}
|
||||
{{=$schemaValue}} !== undefined && (
|
||||
typeof {{=$schemaValue}} != 'number' ||
|
||||
{{?}}
|
||||
(division{{=$lvl}} = {{=$data}} / {{=$schemaValue}},
|
||||
{{? it.opts.multipleOfPrecision }}
|
||||
Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}}
|
||||
{{??}}
|
||||
division{{=$lvl}} !== parseInt(division{{=$lvl}})
|
||||
{{?}}
|
||||
)
|
||||
{{?$isData}} ) {{?}} ) {
|
||||
{{# def.error:'multipleOf' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
43
electron/node_modules/ajv/lib/dot/not.jst
generated
vendored
43
electron/node_modules/ajv/lib/dot/not.jst
generated
vendored
|
|
@ -1,43 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{? {{# def.nonEmptySchema:$schema }} }}
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{
|
||||
$it.createErrors = false;
|
||||
var $allErrorsOption;
|
||||
if ($it.opts.allErrors) {
|
||||
$allErrorsOption = $it.opts.allErrors;
|
||||
$it.opts.allErrors = false;
|
||||
}
|
||||
}}
|
||||
{{= it.validate($it) }}
|
||||
{{
|
||||
$it.createErrors = true;
|
||||
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
|
||||
}}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
if ({{=$nextValid}}) {
|
||||
{{# def.error:'not' }}
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
{{??}}
|
||||
{{# def.addError:'not' }}
|
||||
{{? $breakOnError}}
|
||||
if (false) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
54
electron/node_modules/ajv/lib/dot/oneOf.jst
generated
vendored
54
electron/node_modules/ajv/lib/dot/oneOf.jst
generated
vendored
|
|
@ -1,54 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{
|
||||
var $currentBaseId = $it.baseId
|
||||
, $prevValid = 'prevValid' + $lvl
|
||||
, $passingSchemas = 'passingSchemas' + $lvl;
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors
|
||||
, {{=$prevValid}} = false
|
||||
, {{=$valid}} = false
|
||||
, {{=$passingSchemas}} = null;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
{{??}}
|
||||
var {{=$nextValid}} = true;
|
||||
{{?}}
|
||||
|
||||
{{? $i }}
|
||||
if ({{=$nextValid}} && {{=$prevValid}}) {
|
||||
{{=$valid}} = false;
|
||||
{{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}];
|
||||
} else {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{?}}
|
||||
|
||||
if ({{=$nextValid}}) {
|
||||
{{=$valid}} = {{=$prevValid}} = true;
|
||||
{{=$passingSchemas}} = {{=$i}};
|
||||
}
|
||||
{{~}}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
{{= $closingBraces }}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.extraError:'oneOf' }}
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
25
electron/node_modules/ajv/lib/dot/pattern.jst
generated
vendored
25
electron/node_modules/ajv/lib/dot/pattern.jst
generated
vendored
|
|
@ -1,25 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{
|
||||
var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
|
||||
}}
|
||||
|
||||
{{? $isData }}
|
||||
var {{=$valid}} = true;
|
||||
try {
|
||||
{{=$valid}} = {{=$regExpCode}}({{=$schemaValue}}).test({{=$data}});
|
||||
} catch(e) {
|
||||
{{=$valid}} = false;
|
||||
}
|
||||
if ({{# def.$dataNotType:'string' }} !{{=$valid}}) {
|
||||
{{??}}
|
||||
{{
|
||||
var $regexp = it.usePattern($schema);
|
||||
}}
|
||||
if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) {
|
||||
{{?}}
|
||||
{{# def.error:'pattern' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
245
electron/node_modules/ajv/lib/dot/properties.jst
generated
vendored
245
electron/node_modules/ajv/lib/dot/properties.jst
generated
vendored
|
|
@ -1,245 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.validateAdditional:
|
||||
{{ /* additionalProperties is schema */
|
||||
$it.schema = $aProperties;
|
||||
$it.schemaPath = it.schemaPath + '.additionalProperties';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
|
||||
$it.errorPath = it.opts._errorDataPathProperty
|
||||
? it.errorPath
|
||||
: it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
var $passData = $data + '[' + $key + ']';
|
||||
$it.dataPathArr[$dataNxt] = $key;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
#}}
|
||||
|
||||
|
||||
{{
|
||||
var $key = 'key' + $lvl
|
||||
, $idx = 'idx' + $lvl
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $dataProperties = 'dataProperties' + $lvl;
|
||||
|
||||
var $schemaKeys = Object.keys($schema || {}).filter(notProto)
|
||||
, $pProperties = it.schema.patternProperties || {}
|
||||
, $pPropertyKeys = Object.keys($pProperties).filter(notProto)
|
||||
, $aProperties = it.schema.additionalProperties
|
||||
, $someProperties = $schemaKeys.length || $pPropertyKeys.length
|
||||
, $noAdditional = $aProperties === false
|
||||
, $additionalIsSchema = typeof $aProperties == 'object'
|
||||
&& Object.keys($aProperties).length
|
||||
, $removeAdditional = it.opts.removeAdditional
|
||||
, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional
|
||||
, $ownProperties = it.opts.ownProperties
|
||||
, $currentBaseId = it.baseId;
|
||||
|
||||
var $required = it.schema.required;
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
|
||||
var $requiredHash = it.util.toHash($required);
|
||||
}
|
||||
|
||||
function notProto(p) { return p !== '__proto__'; }
|
||||
}}
|
||||
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$nextValid}} = true;
|
||||
{{? $ownProperties }}
|
||||
var {{=$dataProperties}} = undefined;
|
||||
{{?}}
|
||||
|
||||
{{? $checkAdditional }}
|
||||
{{# def.iterateProperties }}
|
||||
{{? $someProperties }}
|
||||
var isAdditional{{=$lvl}} = !(false
|
||||
{{? $schemaKeys.length }}
|
||||
{{? $schemaKeys.length > 8 }}
|
||||
|| validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}})
|
||||
{{??}}
|
||||
{{~ $schemaKeys:$propertyKey }}
|
||||
|| {{=$key}} == {{= it.util.toQuotedString($propertyKey) }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{? $pPropertyKeys.length }}
|
||||
{{~ $pPropertyKeys:$pProperty:$i }}
|
||||
|| {{= it.usePattern($pProperty) }}.test({{=$key}})
|
||||
{{~}}
|
||||
{{?}}
|
||||
);
|
||||
|
||||
if (isAdditional{{=$lvl}}) {
|
||||
{{?}}
|
||||
{{? $removeAdditional == 'all' }}
|
||||
delete {{=$data}}[{{=$key}}];
|
||||
{{??}}
|
||||
{{
|
||||
var $currentErrorPath = it.errorPath;
|
||||
var $additionalProperty = '\' + ' + $key + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
}
|
||||
}}
|
||||
{{? $noAdditional }}
|
||||
{{? $removeAdditional }}
|
||||
delete {{=$data}}[{{=$key}}];
|
||||
{{??}}
|
||||
{{=$nextValid}} = false;
|
||||
{{
|
||||
var $currErrSchemaPath = $errSchemaPath;
|
||||
$errSchemaPath = it.errSchemaPath + '/additionalProperties';
|
||||
}}
|
||||
{{# def.error:'additionalProperties' }}
|
||||
{{ $errSchemaPath = $currErrSchemaPath; }}
|
||||
{{? $breakOnError }} break; {{?}}
|
||||
{{?}}
|
||||
{{?? $additionalIsSchema }}
|
||||
{{? $removeAdditional == 'failing' }}
|
||||
var {{=$errs}} = errors;
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{# def.validateAdditional }}
|
||||
|
||||
if (!{{=$nextValid}}) {
|
||||
errors = {{=$errs}};
|
||||
if (validate.errors !== null) {
|
||||
if (errors) validate.errors.length = errors;
|
||||
else validate.errors = null;
|
||||
}
|
||||
delete {{=$data}}[{{=$key}}];
|
||||
}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
{{??}}
|
||||
{{# def.validateAdditional }}
|
||||
{{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{ it.errorPath = $currentErrorPath; }}
|
||||
{{?}}
|
||||
{{? $someProperties }}
|
||||
}
|
||||
{{?}}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
|
||||
{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }}
|
||||
|
||||
{{? $schemaKeys.length }}
|
||||
{{~ $schemaKeys:$propertyKey }}
|
||||
{{ var $sch = $schema[$propertyKey]; }}
|
||||
|
||||
{{? {{# def.nonEmptySchema:$sch}} }}
|
||||
{{
|
||||
var $prop = it.util.getProperty($propertyKey)
|
||||
, $passData = $data + $prop
|
||||
, $hasDefault = $useDefaults && $sch.default !== undefined;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + $prop;
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
|
||||
$it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
|
||||
$it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
|
||||
{{? {{# def.willOptimize }} }}
|
||||
{{
|
||||
$code = {{# def._optimizeValidate }};
|
||||
var $useData = $passData;
|
||||
}}
|
||||
{{??}}
|
||||
{{ var $useData = $nextData; }}
|
||||
var {{=$nextData}} = {{=$passData}};
|
||||
{{?}}
|
||||
|
||||
{{? $hasDefault }}
|
||||
{{= $code }}
|
||||
{{??}}
|
||||
{{? $requiredHash && $requiredHash[$propertyKey] }}
|
||||
if ({{# def.noPropertyInData }}) {
|
||||
{{=$nextValid}} = false;
|
||||
{{
|
||||
var $currentErrorPath = it.errorPath
|
||||
, $currErrSchemaPath = $errSchemaPath
|
||||
, $missingProperty = it.util.escapeQuotes($propertyKey);
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
$errSchemaPath = it.errSchemaPath + '/required';
|
||||
}}
|
||||
{{# def.error:'required' }}
|
||||
{{ $errSchemaPath = $currErrSchemaPath; }}
|
||||
{{ it.errorPath = $currentErrorPath; }}
|
||||
} else {
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if ({{# def.noPropertyInData }}) {
|
||||
{{=$nextValid}} = true;
|
||||
} else {
|
||||
{{??}}
|
||||
if ({{=$useData}} !== undefined
|
||||
{{? $ownProperties }}
|
||||
&& {{# def.isOwnProperty }}
|
||||
{{?}}
|
||||
) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{= $code }}
|
||||
}
|
||||
{{?}} {{ /* $hasDefault */ }}
|
||||
{{?}} {{ /* def.nonEmptySchema */ }}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
|
||||
{{? $pPropertyKeys.length }}
|
||||
{{~ $pPropertyKeys:$pProperty }}
|
||||
{{ var $sch = $pProperties[$pProperty]; }}
|
||||
|
||||
{{? {{# def.nonEmptySchema:$sch}} }}
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
|
||||
$it.errSchemaPath = it.errSchemaPath + '/patternProperties/'
|
||||
+ it.util.escapeFragment($pProperty);
|
||||
}}
|
||||
|
||||
{{# def.iterateProperties }}
|
||||
if ({{= it.usePattern($pProperty) }}.test({{=$key}})) {
|
||||
{{
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
var $passData = $data + '[' + $key + ']';
|
||||
$it.dataPathArr[$dataNxt] = $key;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
|
||||
{{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}}
|
||||
}
|
||||
{{? $breakOnError }} else {{=$nextValid}} = true; {{?}}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}} {{ /* def.nonEmptySchema */ }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
52
electron/node_modules/ajv/lib/dot/propertyNames.jst
generated
vendored
52
electron/node_modules/ajv/lib/dot/propertyNames.jst
generated
vendored
|
|
@ -1,52 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
|
||||
{{? {{# def.nonEmptySchema:$schema }} }}
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
|
||||
{{
|
||||
var $key = 'key' + $lvl
|
||||
, $idx = 'idx' + $lvl
|
||||
, $i = 'i' + $lvl
|
||||
, $invalidName = '\' + ' + $key + ' + \''
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $dataProperties = 'dataProperties' + $lvl
|
||||
, $ownProperties = it.opts.ownProperties
|
||||
, $currentBaseId = it.baseId;
|
||||
}}
|
||||
|
||||
{{? $ownProperties }}
|
||||
var {{=$dataProperties}} = undefined;
|
||||
{{?}}
|
||||
{{# def.iterateProperties }}
|
||||
var startErrs{{=$lvl}} = errors;
|
||||
|
||||
{{ var $passData = $key; }}
|
||||
{{# def.setCompositeRule }}
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
if (!{{=$nextValid}}) {
|
||||
for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}<errors; {{=$i}}++) {
|
||||
vErrors[{{=$i}}].propertyName = {{=$key}};
|
||||
}
|
||||
{{# def.extraError:'propertyNames' }}
|
||||
{{? $breakOnError }} break; {{?}}
|
||||
}
|
||||
}
|
||||
{{?}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
||||
85
electron/node_modules/ajv/lib/dot/ref.jst
generated
vendored
85
electron/node_modules/ajv/lib/dot/ref.jst
generated
vendored
|
|
@ -1,85 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
|
||||
{{## def._validateRef:_v:
|
||||
{{? it.opts.passContext }}
|
||||
{{=_v}}.call(this,
|
||||
{{??}}
|
||||
{{=_v}}(
|
||||
{{?}}
|
||||
{{=$data}}, {{# def.dataPath }}{{# def.passParentData }}, rootData)
|
||||
#}}
|
||||
|
||||
{{ var $async, $refCode; }}
|
||||
{{? $schema == '#' || $schema == '#/' }}
|
||||
{{
|
||||
if (it.isRoot) {
|
||||
$async = it.async;
|
||||
$refCode = 'validate';
|
||||
} else {
|
||||
$async = it.root.schema.$async === true;
|
||||
$refCode = 'root.refVal[0]';
|
||||
}
|
||||
}}
|
||||
{{??}}
|
||||
{{ var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); }}
|
||||
{{? $refVal === undefined }}
|
||||
{{ var $message = it.MissingRefError.message(it.baseId, $schema); }}
|
||||
{{? it.opts.missingRefs == 'fail' }}
|
||||
{{ it.logger.error($message); }}
|
||||
{{# def.error:'$ref' }}
|
||||
{{? $breakOnError }} if (false) { {{?}}
|
||||
{{?? it.opts.missingRefs == 'ignore' }}
|
||||
{{ it.logger.warn($message); }}
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{??}}
|
||||
{{ throw new it.MissingRefError(it.baseId, $schema, $message); }}
|
||||
{{?}}
|
||||
{{?? $refVal.inline }}
|
||||
{{# def.setupNextLevel }}
|
||||
{{
|
||||
$it.schema = $refVal.schema;
|
||||
$it.schemaPath = '';
|
||||
$it.errSchemaPath = $schema;
|
||||
}}
|
||||
{{ var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); }}
|
||||
{{= $code }}
|
||||
{{? $breakOnError}}
|
||||
if ({{=$nextValid}}) {
|
||||
{{?}}
|
||||
{{??}}
|
||||
{{
|
||||
$async = $refVal.$async === true || (it.async && $refVal.$async !== false);
|
||||
$refCode = $refVal.code;
|
||||
}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $refCode }}
|
||||
{{# def.beginDefOut}}
|
||||
{{# def._validateRef:$refCode }}
|
||||
{{# def.storeDefOut:__callValidate }}
|
||||
|
||||
{{? $async }}
|
||||
{{ if (!it.async) throw new Error('async schema referenced by sync schema'); }}
|
||||
{{? $breakOnError }} var {{=$valid}}; {{?}}
|
||||
try {
|
||||
await {{=__callValidate}};
|
||||
{{? $breakOnError }} {{=$valid}} = true; {{?}}
|
||||
} catch (e) {
|
||||
if (!(e instanceof ValidationError)) throw e;
|
||||
if (vErrors === null) vErrors = e.errors;
|
||||
else vErrors = vErrors.concat(e.errors);
|
||||
errors = vErrors.length;
|
||||
{{? $breakOnError }} {{=$valid}} = false; {{?}}
|
||||
}
|
||||
{{? $breakOnError }} if ({{=$valid}}) { {{?}}
|
||||
{{??}}
|
||||
if (!{{=__callValidate}}) {
|
||||
if (vErrors === null) vErrors = {{=$refCode}}.errors;
|
||||
else vErrors = vErrors.concat({{=$refCode}}.errors);
|
||||
errors = vErrors.length;
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
108
electron/node_modules/ajv/lib/dot/required.jst
generated
vendored
108
electron/node_modules/ajv/lib/dot/required.jst
generated
vendored
|
|
@ -1,108 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.missing }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{ var $vSchema = 'schema' + $lvl; }}
|
||||
|
||||
{{## def.setupLoop:
|
||||
{{? !$isData }}
|
||||
var {{=$vSchema}} = validate.schema{{=$schemaPath}};
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
var $i = 'i' + $lvl
|
||||
, $propertyPath = 'schema' + $lvl + '[' + $i + ']'
|
||||
, $missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
|
||||
}
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.isRequiredOwnProperty:
|
||||
Object.prototype.hasOwnProperty.call({{=$data}}, {{=$vSchema}}[{{=$i}}])
|
||||
#}}
|
||||
|
||||
|
||||
{{? !$isData }}
|
||||
{{? $schema.length < it.opts.loopRequired &&
|
||||
it.schema.properties && Object.keys(it.schema.properties).length }}
|
||||
{{ var $required = []; }}
|
||||
{{~ $schema:$property }}
|
||||
{{ var $propertySch = it.schema.properties[$property]; }}
|
||||
{{? !($propertySch && {{# def.nonEmptySchema:$propertySch}}) }}
|
||||
{{ $required[$required.length] = $property; }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
{{??}}
|
||||
{{ var $required = $schema; }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
|
||||
{{? $isData || $required.length }}
|
||||
{{
|
||||
var $currentErrorPath = it.errorPath
|
||||
, $loopRequired = $isData || $required.length >= it.opts.loopRequired
|
||||
, $ownProperties = it.opts.ownProperties;
|
||||
}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
var missing{{=$lvl}};
|
||||
{{? $loopRequired }}
|
||||
{{# def.setupLoop }}
|
||||
var {{=$valid}} = true;
|
||||
|
||||
{{?$isData}}{{# def.check$dataIsArray }}{{?}}
|
||||
|
||||
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
|
||||
{{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined
|
||||
{{? $ownProperties }}
|
||||
&& {{# def.isRequiredOwnProperty }}
|
||||
{{?}};
|
||||
if (!{{=$valid}}) break;
|
||||
}
|
||||
|
||||
{{? $isData }} } {{?}}
|
||||
|
||||
{{# def.checkError:'required' }}
|
||||
else {
|
||||
{{??}}
|
||||
if ({{# def.checkMissingProperty:$required }}) {
|
||||
{{# def.errorMissingProperty:'required' }}
|
||||
} else {
|
||||
{{?}}
|
||||
{{??}}
|
||||
{{? $loopRequired }}
|
||||
{{# def.setupLoop }}
|
||||
{{? $isData }}
|
||||
if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) {
|
||||
{{# def.addError:'required' }}
|
||||
} else if ({{=$vSchema}} !== undefined) {
|
||||
{{?}}
|
||||
|
||||
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
|
||||
if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined
|
||||
{{? $ownProperties }}
|
||||
|| !{{# def.isRequiredOwnProperty }}
|
||||
{{?}}) {
|
||||
{{# def.addError:'required' }}
|
||||
}
|
||||
}
|
||||
|
||||
{{? $isData }} } {{?}}
|
||||
{{??}}
|
||||
{{~ $required:$propertyKey }}
|
||||
{{# def.allErrorsMissingProperty:'required' }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{ it.errorPath = $currentErrorPath; }}
|
||||
|
||||
{{?? $breakOnError }}
|
||||
if (true) {
|
||||
{{?}}
|
||||
62
electron/node_modules/ajv/lib/dot/uniqueItems.jst
generated
vendored
62
electron/node_modules/ajv/lib/dot/uniqueItems.jst
generated
vendored
|
|
@ -1,62 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
|
||||
{{? ($schema || $isData) && it.opts.uniqueItems !== false }}
|
||||
{{? $isData }}
|
||||
var {{=$valid}};
|
||||
if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined)
|
||||
{{=$valid}} = true;
|
||||
else if (typeof {{=$schemaValue}} != 'boolean')
|
||||
{{=$valid}} = false;
|
||||
else {
|
||||
{{?}}
|
||||
|
||||
var i = {{=$data}}.length
|
||||
, {{=$valid}} = true
|
||||
, j;
|
||||
if (i > 1) {
|
||||
{{
|
||||
var $itemType = it.schema.items && it.schema.items.type
|
||||
, $typeIsArray = Array.isArray($itemType);
|
||||
}}
|
||||
{{? !$itemType || $itemType == 'object' || $itemType == 'array' ||
|
||||
($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }}
|
||||
outer:
|
||||
for (;i--;) {
|
||||
for (j = i; j--;) {
|
||||
if (equal({{=$data}}[i], {{=$data}}[j])) {
|
||||
{{=$valid}} = false;
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
{{??}}
|
||||
var itemIndices = {}, item;
|
||||
for (;i--;) {
|
||||
var item = {{=$data}}[i];
|
||||
{{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }}
|
||||
if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue;
|
||||
{{? $typeIsArray}}
|
||||
if (typeof item == 'string') item = '"' + item;
|
||||
{{?}}
|
||||
if (typeof itemIndices[item] == 'number') {
|
||||
{{=$valid}} = false;
|
||||
j = itemIndices[item];
|
||||
break;
|
||||
}
|
||||
itemIndices[item] = i;
|
||||
}
|
||||
{{?}}
|
||||
}
|
||||
|
||||
{{? $isData }} } {{?}}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.error:'uniqueItems' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
{{??}}
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{?}}
|
||||
276
electron/node_modules/ajv/lib/dot/validate.jst
generated
vendored
276
electron/node_modules/ajv/lib/dot/validate.jst
generated
vendored
|
|
@ -1,276 +0,0 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.defaults }}
|
||||
{{# def.coerce }}
|
||||
|
||||
{{ /**
|
||||
* schema compilation (render) time:
|
||||
* it = { schema, RULES, _validate, opts }
|
||||
* it.validate - this template function,
|
||||
* it is used recursively to generate code for subschemas
|
||||
*
|
||||
* runtime:
|
||||
* "validate" is a variable name to which this function will be assigned
|
||||
* validateRef etc. are defined in the parent scope in index.js
|
||||
*/ }}
|
||||
|
||||
{{
|
||||
var $async = it.schema.$async === true
|
||||
, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref')
|
||||
, $id = it.self._getId(it.schema);
|
||||
}}
|
||||
|
||||
{{
|
||||
if (it.opts.strictKeywords) {
|
||||
var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
|
||||
if ($unknownKwd) {
|
||||
var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
|
||||
if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
|
||||
else throw new Error($keywordsMsg);
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
{{? it.isTop }}
|
||||
var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) {
|
||||
'use strict';
|
||||
{{? $id && (it.opts.sourceCode || it.opts.processCode) }}
|
||||
{{= '/\*# sourceURL=' + $id + ' */' }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }}
|
||||
{{ var $keyword = 'false schema'; }}
|
||||
{{# def.setupKeyword }}
|
||||
{{? it.schema === false}}
|
||||
{{? it.isTop}}
|
||||
{{ $breakOnError = true; }}
|
||||
{{??}}
|
||||
var {{=$valid}} = false;
|
||||
{{?}}
|
||||
{{# def.error:'false schema' }}
|
||||
{{??}}
|
||||
{{? it.isTop}}
|
||||
{{? $async }}
|
||||
return data;
|
||||
{{??}}
|
||||
validate.errors = null;
|
||||
return true;
|
||||
{{?}}
|
||||
{{??}}
|
||||
var {{=$valid}} = true;
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? it.isTop}}
|
||||
};
|
||||
return validate;
|
||||
{{?}}
|
||||
|
||||
{{ return out; }}
|
||||
{{?}}
|
||||
|
||||
|
||||
{{? it.isTop }}
|
||||
{{
|
||||
var $top = it.isTop
|
||||
, $lvl = it.level = 0
|
||||
, $dataLvl = it.dataLevel = 0
|
||||
, $data = 'data';
|
||||
it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
|
||||
it.baseId = it.baseId || it.rootId;
|
||||
delete it.isTop;
|
||||
|
||||
it.dataPathArr = [""];
|
||||
|
||||
if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored in the schema root';
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
}}
|
||||
|
||||
var vErrors = null; {{ /* don't edit, used in replace */ }}
|
||||
var errors = 0; {{ /* don't edit, used in replace */ }}
|
||||
if (rootData === undefined) rootData = data; {{ /* don't edit, used in replace */ }}
|
||||
{{??}}
|
||||
{{
|
||||
var $lvl = it.level
|
||||
, $dataLvl = it.dataLevel
|
||||
, $data = 'data' + ($dataLvl || '');
|
||||
|
||||
if ($id) it.baseId = it.resolve.url(it.baseId, $id);
|
||||
|
||||
if ($async && !it.async) throw new Error('async schema in sync schema');
|
||||
}}
|
||||
|
||||
var errs_{{=$lvl}} = errors;
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
var $valid = 'valid' + $lvl
|
||||
, $breakOnError = !it.opts.allErrors
|
||||
, $closingBraces1 = ''
|
||||
, $closingBraces2 = '';
|
||||
|
||||
var $errorKeyword;
|
||||
var $typeSchema = it.schema.type
|
||||
, $typeIsArray = Array.isArray($typeSchema);
|
||||
|
||||
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
|
||||
if ($typeIsArray) {
|
||||
if ($typeSchema.indexOf('null') == -1)
|
||||
$typeSchema = $typeSchema.concat('null');
|
||||
} else if ($typeSchema != 'null') {
|
||||
$typeSchema = [$typeSchema, 'null'];
|
||||
$typeIsArray = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($typeIsArray && $typeSchema.length == 1) {
|
||||
$typeSchema = $typeSchema[0];
|
||||
$typeIsArray = false;
|
||||
}
|
||||
}}
|
||||
|
||||
{{## def.checkType:
|
||||
{{
|
||||
var $schemaPath = it.schemaPath + '.type'
|
||||
, $errSchemaPath = it.errSchemaPath + '/type'
|
||||
, $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
|
||||
}}
|
||||
|
||||
if ({{= it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) }}) {
|
||||
#}}
|
||||
|
||||
{{? it.schema.$ref && $refKeywords }}
|
||||
{{? it.opts.extendRefs == 'fail' }}
|
||||
{{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); }}
|
||||
{{?? it.opts.extendRefs !== true }}
|
||||
{{
|
||||
$refKeywords = false;
|
||||
it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
|
||||
}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? it.schema.$comment && it.opts.$comment }}
|
||||
{{= it.RULES.all.$comment.code(it, '$comment') }}
|
||||
{{?}}
|
||||
|
||||
{{? $typeSchema }}
|
||||
{{? it.opts.coerceTypes }}
|
||||
{{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }}
|
||||
{{?}}
|
||||
|
||||
{{ var $rulesGroup = it.RULES.types[$typeSchema]; }}
|
||||
{{? $coerceToTypes || $typeIsArray || $rulesGroup === true ||
|
||||
($rulesGroup && !$shouldUseGroup($rulesGroup)) }}
|
||||
{{
|
||||
var $schemaPath = it.schemaPath + '.type'
|
||||
, $errSchemaPath = it.errSchemaPath + '/type';
|
||||
}}
|
||||
{{# def.checkType }}
|
||||
{{? $coerceToTypes }}
|
||||
{{# def.coerceType }}
|
||||
{{??}}
|
||||
{{# def.error:'type' }}
|
||||
{{?}}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
|
||||
{{? it.schema.$ref && !$refKeywords }}
|
||||
{{= it.RULES.all.$ref.code(it, '$ref') }}
|
||||
{{? $breakOnError }}
|
||||
}
|
||||
if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) {
|
||||
{{ $closingBraces2 += '}'; }}
|
||||
{{?}}
|
||||
{{??}}
|
||||
{{~ it.RULES:$rulesGroup }}
|
||||
{{? $shouldUseGroup($rulesGroup) }}
|
||||
{{? $rulesGroup.type }}
|
||||
if ({{= it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) }}) {
|
||||
{{?}}
|
||||
{{? it.opts.useDefaults }}
|
||||
{{? $rulesGroup.type == 'object' && it.schema.properties }}
|
||||
{{# def.defaultProperties }}
|
||||
{{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }}
|
||||
{{# def.defaultItems }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{~ $rulesGroup.rules:$rule }}
|
||||
{{? $shouldUseRule($rule) }}
|
||||
{{ var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); }}
|
||||
{{? $code }}
|
||||
{{= $code }}
|
||||
{{? $breakOnError }}
|
||||
{{ $closingBraces1 += '}'; }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{~}}
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces1 }}
|
||||
{{ $closingBraces1 = ''; }}
|
||||
{{?}}
|
||||
{{? $rulesGroup.type }}
|
||||
}
|
||||
{{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }}
|
||||
else {
|
||||
{{
|
||||
var $schemaPath = it.schemaPath + '.type'
|
||||
, $errSchemaPath = it.errSchemaPath + '/type';
|
||||
}}
|
||||
{{# def.error:'type' }}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) {
|
||||
{{ $closingBraces2 += '}'; }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{~}}
|
||||
{{?}}
|
||||
|
||||
{{? $breakOnError }} {{= $closingBraces2 }} {{?}}
|
||||
|
||||
{{? $top }}
|
||||
{{? $async }}
|
||||
if (errors === 0) return data; {{ /* don't edit, used in replace */ }}
|
||||
else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }}
|
||||
{{??}}
|
||||
validate.errors = vErrors; {{ /* don't edit, used in replace */ }}
|
||||
return errors === 0; {{ /* don't edit, used in replace */ }}
|
||||
{{?}}
|
||||
};
|
||||
|
||||
return validate;
|
||||
{{??}}
|
||||
var {{=$valid}} = errors === errs_{{=$lvl}};
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
function $shouldUseGroup($rulesGroup) {
|
||||
var rules = $rulesGroup.rules;
|
||||
for (var i=0; i < rules.length; i++)
|
||||
if ($shouldUseRule(rules[i]))
|
||||
return true;
|
||||
}
|
||||
|
||||
function $shouldUseRule($rule) {
|
||||
return it.schema[$rule.keyword] !== undefined ||
|
||||
($rule.implements && $ruleImplementsSomeKeyword($rule));
|
||||
}
|
||||
|
||||
function $ruleImplementsSomeKeyword($rule) {
|
||||
var impl = $rule.implements;
|
||||
for (var i=0; i < impl.length; i++)
|
||||
if (it.schema[impl[i]] !== undefined)
|
||||
return true;
|
||||
}
|
||||
}}
|
||||
3
electron/node_modules/ajv/lib/dotjs/README.md
generated
vendored
3
electron/node_modules/ajv/lib/dotjs/README.md
generated
vendored
|
|
@ -1,3 +0,0 @@
|
|||
These files are compiled dot templates from dot folder.
|
||||
|
||||
Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder.
|
||||
163
electron/node_modules/ajv/lib/dotjs/_limit.js
generated
vendored
163
electron/node_modules/ajv/lib/dotjs/_limit.js
generated
vendored
|
|
@ -1,163 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate__limit(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $isMax = $keyword == 'maximum',
|
||||
$exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
|
||||
$schemaExcl = it.schema[$exclusiveKeyword],
|
||||
$isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
|
||||
$op = $isMax ? '<' : '>',
|
||||
$notOp = $isMax ? '>' : '<',
|
||||
$errorKeyword = undefined;
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
if ($isDataExcl) {
|
||||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
|
||||
$exclusive = 'exclusive' + $lvl,
|
||||
$exclType = 'exclType' + $lvl,
|
||||
$exclIsNumber = 'exclIsNumber' + $lvl,
|
||||
$opExpr = 'op' + $lvl,
|
||||
$opStr = '\' + ' + $opExpr + ' + \'';
|
||||
out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
|
||||
$schemaValueExcl = 'schemaExcl' + $lvl;
|
||||
out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
|
||||
var $errorKeyword = $exclusiveKeyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } else if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
|
||||
if ($schema === undefined) {
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
$schemaValue = $schemaValueExcl;
|
||||
$isData = $isDataExcl;
|
||||
}
|
||||
} else {
|
||||
var $exclIsNumber = typeof $schemaExcl == 'number',
|
||||
$opStr = $op;
|
||||
if ($exclIsNumber && $isData) {
|
||||
var $opExpr = '\'' + $opStr + '\'';
|
||||
out += ' if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
|
||||
} else {
|
||||
if ($exclIsNumber && $schema === undefined) {
|
||||
$exclusive = true;
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
$schemaValue = $schemaExcl;
|
||||
$notOp += '=';
|
||||
} else {
|
||||
if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
|
||||
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
|
||||
$exclusive = true;
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
$notOp += '=';
|
||||
} else {
|
||||
$exclusive = false;
|
||||
$opStr += '=';
|
||||
}
|
||||
}
|
||||
var $opExpr = '\'' + $opStr + '\'';
|
||||
out += ' if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
|
||||
}
|
||||
}
|
||||
$errorKeyword = $errorKeyword || $keyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be ' + ($opStr) + ' ';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue);
|
||||
} else {
|
||||
out += '' + ($schemaValue) + '\'';
|
||||
}
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
80
electron/node_modules/ajv/lib/dotjs/_limitItems.js
generated
vendored
80
electron/node_modules/ajv/lib/dotjs/_limitItems.js
generated
vendored
|
|
@ -1,80 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate__limitItems(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxItems' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
|
||||
var $errorKeyword = $keyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT have ';
|
||||
if ($keyword == 'maxItems') {
|
||||
out += 'more';
|
||||
} else {
|
||||
out += 'fewer';
|
||||
}
|
||||
out += ' than ';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue) + ' + \'';
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' items\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += '} ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
85
electron/node_modules/ajv/lib/dotjs/_limitLength.js
generated
vendored
85
electron/node_modules/ajv/lib/dotjs/_limitLength.js
generated
vendored
|
|
@ -1,85 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate__limitLength(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxLength' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
if (it.opts.unicode === false) {
|
||||
out += ' ' + ($data) + '.length ';
|
||||
} else {
|
||||
out += ' ucs2length(' + ($data) + ') ';
|
||||
}
|
||||
out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
|
||||
var $errorKeyword = $keyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT be ';
|
||||
if ($keyword == 'maxLength') {
|
||||
out += 'longer';
|
||||
} else {
|
||||
out += 'shorter';
|
||||
}
|
||||
out += ' than ';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue) + ' + \'';
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' characters\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += '} ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
80
electron/node_modules/ajv/lib/dotjs/_limitProperties.js
generated
vendored
80
electron/node_modules/ajv/lib/dotjs/_limitProperties.js
generated
vendored
|
|
@ -1,80 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
var $op = $keyword == 'maxProperties' ? '>' : '<';
|
||||
out += 'if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
|
||||
}
|
||||
out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
|
||||
var $errorKeyword = $keyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT have ';
|
||||
if ($keyword == 'maxProperties') {
|
||||
out += 'more';
|
||||
} else {
|
||||
out += 'fewer';
|
||||
}
|
||||
out += ' than ';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue) + ' + \'';
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' properties\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += '} ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
42
electron/node_modules/ajv/lib/dotjs/allOf.js
generated
vendored
42
electron/node_modules/ajv/lib/dotjs/allOf.js
generated
vendored
|
|
@ -1,42 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_allOf(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $currentBaseId = $it.baseId,
|
||||
$allSchemasEmpty = true;
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $sch, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$sch = arr1[$i += 1];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
$allSchemasEmpty = false;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
if ($allSchemasEmpty) {
|
||||
out += ' if (true) { ';
|
||||
} else {
|
||||
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
73
electron/node_modules/ajv/lib/dotjs/anyOf.js
generated
vendored
73
electron/node_modules/ajv/lib/dotjs/anyOf.js
generated
vendored
|
|
@ -1,73 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_anyOf(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $noEmptySchema = $schema.every(function($sch) {
|
||||
return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all));
|
||||
});
|
||||
if ($noEmptySchema) {
|
||||
var $currentBaseId = $it.baseId;
|
||||
out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $sch, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$sch = arr1[$i += 1];
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should match some schema in anyOf\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; return false; ';
|
||||
}
|
||||
}
|
||||
out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
14
electron/node_modules/ajv/lib/dotjs/comment.js
generated
vendored
14
electron/node_modules/ajv/lib/dotjs/comment.js
generated
vendored
|
|
@ -1,14 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_comment(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $schema = it.schema[$keyword];
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $comment = it.util.toQuotedString($schema);
|
||||
if (it.opts.$comment === true) {
|
||||
out += ' console.log(' + ($comment) + ');';
|
||||
} else if (typeof it.opts.$comment == 'function') {
|
||||
out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
56
electron/node_modules/ajv/lib/dotjs/const.js
generated
vendored
56
electron/node_modules/ajv/lib/dotjs/const.js
generated
vendored
|
|
@ -1,56 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_const(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!$isData) {
|
||||
out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
|
||||
}
|
||||
out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be equal to constant\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' }';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
81
electron/node_modules/ajv/lib/dotjs/contains.js
generated
vendored
81
electron/node_modules/ajv/lib/dotjs/contains.js
generated
vendored
|
|
@ -1,81 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_contains(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $idx = 'i' + $lvl,
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$currentBaseId = it.baseId,
|
||||
$nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all));
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
|
||||
if ($nonEmptySchema) {
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
out += ' if (' + ($nextValid) + ') break; } ';
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
|
||||
} else {
|
||||
out += ' if (' + ($data) + '.length == 0) {';
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should contain a valid item\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } else { ';
|
||||
if ($nonEmptySchema) {
|
||||
out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
|
||||
}
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
228
electron/node_modules/ajv/lib/dotjs/custom.js
generated
vendored
228
electron/node_modules/ajv/lib/dotjs/custom.js
generated
vendored
|
|
@ -1,228 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_custom(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $rule = this,
|
||||
$definition = 'definition' + $lvl,
|
||||
$rDef = $rule.definition,
|
||||
$closingBraces = '';
|
||||
var $compile, $inline, $macro, $ruleValidate, $validateCode;
|
||||
if ($isData && $rDef.$data) {
|
||||
$validateCode = 'keywordValidate' + $lvl;
|
||||
var $validateSchema = $rDef.validateSchema;
|
||||
out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
|
||||
} else {
|
||||
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
|
||||
if (!$ruleValidate) return;
|
||||
$schemaValue = 'validate.schema' + $schemaPath;
|
||||
$validateCode = $ruleValidate.code;
|
||||
$compile = $rDef.compile;
|
||||
$inline = $rDef.inline;
|
||||
$macro = $rDef.macro;
|
||||
}
|
||||
var $ruleErrs = $validateCode + '.errors',
|
||||
$i = 'i' + $lvl,
|
||||
$ruleErr = 'ruleErr' + $lvl,
|
||||
$asyncKeyword = $rDef.async;
|
||||
if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
|
||||
if (!($inline || $macro)) {
|
||||
out += '' + ($ruleErrs) + ' = null;';
|
||||
}
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
|
||||
if ($isData && $rDef.$data) {
|
||||
$closingBraces += '}';
|
||||
out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
|
||||
if ($validateSchema) {
|
||||
$closingBraces += '}';
|
||||
out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
|
||||
}
|
||||
}
|
||||
if ($inline) {
|
||||
if ($rDef.statements) {
|
||||
out += ' ' + ($ruleValidate.validate) + ' ';
|
||||
} else {
|
||||
out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
|
||||
}
|
||||
} else if ($macro) {
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
$it.schema = $ruleValidate.validate;
|
||||
$it.schemaPath = '';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += ' ' + ($code);
|
||||
} else {
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = '';
|
||||
out += ' ' + ($validateCode) + '.call( ';
|
||||
if (it.opts.passContext) {
|
||||
out += 'this';
|
||||
} else {
|
||||
out += 'self';
|
||||
}
|
||||
if ($compile || $rDef.schema === false) {
|
||||
out += ' , ' + ($data) + ' ';
|
||||
} else {
|
||||
out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
|
||||
}
|
||||
out += ' , (dataPath || \'\')';
|
||||
if (it.errorPath != '""') {
|
||||
out += ' + ' + (it.errorPath);
|
||||
}
|
||||
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
|
||||
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
|
||||
out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
|
||||
var def_callRuleValidate = out;
|
||||
out = $$outStack.pop();
|
||||
if ($rDef.errors === false) {
|
||||
out += ' ' + ($valid) + ' = ';
|
||||
if ($asyncKeyword) {
|
||||
out += 'await ';
|
||||
}
|
||||
out += '' + (def_callRuleValidate) + '; ';
|
||||
} else {
|
||||
if ($asyncKeyword) {
|
||||
$ruleErrs = 'customErrors' + $lvl;
|
||||
out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
|
||||
} else {
|
||||
out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($rDef.modifying) {
|
||||
out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
|
||||
}
|
||||
out += '' + ($closingBraces);
|
||||
if ($rDef.valid) {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
} else {
|
||||
out += ' if ( ';
|
||||
if ($rDef.valid === undefined) {
|
||||
out += ' !';
|
||||
if ($macro) {
|
||||
out += '' + ($nextValid);
|
||||
} else {
|
||||
out += '' + ($valid);
|
||||
}
|
||||
} else {
|
||||
out += ' ' + (!$rDef.valid) + ' ';
|
||||
}
|
||||
out += ') { ';
|
||||
$errorKeyword = $rule.keyword;
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = '';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
var def_customError = out;
|
||||
out = $$outStack.pop();
|
||||
if ($inline) {
|
||||
if ($rDef.errors) {
|
||||
if ($rDef.errors != 'full') {
|
||||
out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
|
||||
if (it.opts.verbose) {
|
||||
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
|
||||
}
|
||||
out += ' } ';
|
||||
}
|
||||
} else {
|
||||
if ($rDef.errors === false) {
|
||||
out += ' ' + (def_customError) + ' ';
|
||||
} else {
|
||||
out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
|
||||
if (it.opts.verbose) {
|
||||
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
|
||||
}
|
||||
out += ' } } ';
|
||||
}
|
||||
}
|
||||
} else if ($macro) {
|
||||
out += ' var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; return false; ';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if ($rDef.errors === false) {
|
||||
out += ' ' + (def_customError) + ' ';
|
||||
} else {
|
||||
out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; ';
|
||||
if (it.opts.verbose) {
|
||||
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
|
||||
}
|
||||
out += ' } } else { ' + (def_customError) + ' } ';
|
||||
}
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
168
electron/node_modules/ajv/lib/dotjs/dependencies.js
generated
vendored
168
electron/node_modules/ajv/lib/dotjs/dependencies.js
generated
vendored
|
|
@ -1,168 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_dependencies(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $schemaDeps = {},
|
||||
$propertyDeps = {},
|
||||
$ownProperties = it.opts.ownProperties;
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
}
|
||||
out += 'var ' + ($errs) + ' = errors;';
|
||||
var $currentErrorPath = it.errorPath;
|
||||
out += 'var missing' + ($lvl) + ';';
|
||||
for (var $property in $propertyDeps) {
|
||||
$deps = $propertyDeps[$property];
|
||||
if ($deps.length) {
|
||||
out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' && ( ';
|
||||
var arr1 = $deps;
|
||||
if (arr1) {
|
||||
var $propertyKey, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$propertyKey = arr1[$i += 1];
|
||||
if ($i) {
|
||||
out += ' || ';
|
||||
}
|
||||
var $prop = it.util.getProperty($propertyKey),
|
||||
$useData = $data + $prop;
|
||||
out += ' ( ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
|
||||
}
|
||||
}
|
||||
out += ')) { ';
|
||||
var $propertyPath = 'missing' + $lvl,
|
||||
$missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should have ';
|
||||
if ($deps.length == 1) {
|
||||
out += 'property ' + (it.util.escapeQuotes($deps[0]));
|
||||
} else {
|
||||
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
|
||||
}
|
||||
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
} else {
|
||||
out += ' ) { ';
|
||||
var arr2 = $deps;
|
||||
if (arr2) {
|
||||
var $propertyKey, i2 = -1,
|
||||
l2 = arr2.length - 1;
|
||||
while (i2 < l2) {
|
||||
$propertyKey = arr2[i2 += 1];
|
||||
var $prop = it.util.getProperty($propertyKey),
|
||||
$missingProperty = it.util.escapeQuotes($propertyKey),
|
||||
$useData = $data + $prop;
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
out += ' if ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should have ';
|
||||
if ($deps.length == 1) {
|
||||
out += 'property ' + (it.util.escapeQuotes($deps[0]));
|
||||
} else {
|
||||
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
|
||||
}
|
||||
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
|
||||
}
|
||||
}
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
$closingBraces += '}';
|
||||
out += ' else { ';
|
||||
}
|
||||
}
|
||||
}
|
||||
it.errorPath = $currentErrorPath;
|
||||
var $currentBaseId = $it.baseId;
|
||||
for (var $property in $schemaDeps) {
|
||||
var $sch = $schemaDeps[$property];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
|
||||
}
|
||||
out += ') { ';
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + it.util.getProperty($property);
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
66
electron/node_modules/ajv/lib/dotjs/enum.js
generated
vendored
66
electron/node_modules/ajv/lib/dotjs/enum.js
generated
vendored
|
|
@ -1,66 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_enum(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $i = 'i' + $lvl,
|
||||
$vSchema = 'schema' + $lvl;
|
||||
if (!$isData) {
|
||||
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
|
||||
}
|
||||
out += 'var ' + ($valid) + ';';
|
||||
if ($isData) {
|
||||
out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
|
||||
}
|
||||
out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
|
||||
if ($isData) {
|
||||
out += ' } ';
|
||||
}
|
||||
out += ' if (!' + ($valid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be equal to one of the allowed values\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' }';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
150
electron/node_modules/ajv/lib/dotjs/format.js
generated
vendored
150
electron/node_modules/ajv/lib/dotjs/format.js
generated
vendored
|
|
@ -1,150 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_format(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
if (it.opts.format === false) {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $unknownFormats = it.opts.unknownFormats,
|
||||
$allowUnknown = Array.isArray($unknownFormats);
|
||||
if ($isData) {
|
||||
var $format = 'format' + $lvl,
|
||||
$isObject = 'isObject' + $lvl,
|
||||
$formatType = 'formatType' + $lvl;
|
||||
out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
|
||||
if (it.async) {
|
||||
out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
|
||||
}
|
||||
out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
|
||||
}
|
||||
out += ' (';
|
||||
if ($unknownFormats != 'ignore') {
|
||||
out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
|
||||
if ($allowUnknown) {
|
||||
out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
|
||||
}
|
||||
out += ') || ';
|
||||
}
|
||||
out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
|
||||
if (it.async) {
|
||||
out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
|
||||
} else {
|
||||
out += ' ' + ($format) + '(' + ($data) + ') ';
|
||||
}
|
||||
out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
|
||||
} else {
|
||||
var $format = it.formats[$schema];
|
||||
if (!$format) {
|
||||
if ($unknownFormats == 'ignore') {
|
||||
it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
return out;
|
||||
} else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
return out;
|
||||
} else {
|
||||
throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
|
||||
}
|
||||
}
|
||||
var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
|
||||
var $formatType = $isObject && $format.type || 'string';
|
||||
if ($isObject) {
|
||||
var $async = $format.async === true;
|
||||
$format = $format.validate;
|
||||
}
|
||||
if ($formatType != $ruleType) {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if ($async) {
|
||||
if (!it.async) throw new Error('async format in sync schema');
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
|
||||
out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
|
||||
} else {
|
||||
out += ' if (! ';
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema);
|
||||
if ($isObject) $formatRef += '.validate';
|
||||
if (typeof $format == 'function') {
|
||||
out += ' ' + ($formatRef) + '(' + ($data) + ') ';
|
||||
} else {
|
||||
out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
|
||||
}
|
||||
out += ') { ';
|
||||
}
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
|
||||
if ($isData) {
|
||||
out += '' + ($schemaValue);
|
||||
} else {
|
||||
out += '' + (it.util.toQuotedString($schema));
|
||||
}
|
||||
out += ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should match format "';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue) + ' + \'';
|
||||
} else {
|
||||
out += '' + (it.util.escapeQuotes($schema));
|
||||
}
|
||||
out += '"\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + (it.util.toQuotedString($schema));
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
103
electron/node_modules/ajv/lib/dotjs/if.js
generated
vendored
103
electron/node_modules/ajv/lib/dotjs/if.js
generated
vendored
|
|
@ -1,103 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_if(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $thenSch = it.schema['then'],
|
||||
$elseSch = it.schema['else'],
|
||||
$thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)),
|
||||
$elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)),
|
||||
$currentBaseId = $it.baseId;
|
||||
if ($thenPresent || $elsePresent) {
|
||||
var $ifClause;
|
||||
$it.createErrors = false;
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
$it.createErrors = true;
|
||||
out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
if ($thenPresent) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$it.schema = it.schema['then'];
|
||||
$it.schemaPath = it.schemaPath + '.then';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/then';
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
|
||||
if ($thenPresent && $elsePresent) {
|
||||
$ifClause = 'ifClause' + $lvl;
|
||||
out += ' var ' + ($ifClause) + ' = \'then\'; ';
|
||||
} else {
|
||||
$ifClause = '\'then\'';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($elsePresent) {
|
||||
out += ' else { ';
|
||||
}
|
||||
} else {
|
||||
out += ' if (!' + ($nextValid) + ') { ';
|
||||
}
|
||||
if ($elsePresent) {
|
||||
$it.schema = it.schema['else'];
|
||||
$it.schemaPath = it.schemaPath + '.else';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/else';
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
|
||||
if ($thenPresent && $elsePresent) {
|
||||
$ifClause = 'ifClause' + $lvl;
|
||||
out += ' var ' + ($ifClause) + ' = \'else\'; ';
|
||||
} else {
|
||||
$ifClause = '\'else\'';
|
||||
}
|
||||
out += ' } ';
|
||||
}
|
||||
out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; return false; ';
|
||||
}
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
33
electron/node_modules/ajv/lib/dotjs/index.js
generated
vendored
33
electron/node_modules/ajv/lib/dotjs/index.js
generated
vendored
|
|
@ -1,33 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
//all requires must be explicit because browserify won't work with dynamic requires
|
||||
module.exports = {
|
||||
'$ref': require('./ref'),
|
||||
allOf: require('./allOf'),
|
||||
anyOf: require('./anyOf'),
|
||||
'$comment': require('./comment'),
|
||||
const: require('./const'),
|
||||
contains: require('./contains'),
|
||||
dependencies: require('./dependencies'),
|
||||
'enum': require('./enum'),
|
||||
format: require('./format'),
|
||||
'if': require('./if'),
|
||||
items: require('./items'),
|
||||
maximum: require('./_limit'),
|
||||
minimum: require('./_limit'),
|
||||
maxItems: require('./_limitItems'),
|
||||
minItems: require('./_limitItems'),
|
||||
maxLength: require('./_limitLength'),
|
||||
minLength: require('./_limitLength'),
|
||||
maxProperties: require('./_limitProperties'),
|
||||
minProperties: require('./_limitProperties'),
|
||||
multipleOf: require('./multipleOf'),
|
||||
not: require('./not'),
|
||||
oneOf: require('./oneOf'),
|
||||
pattern: require('./pattern'),
|
||||
properties: require('./properties'),
|
||||
propertyNames: require('./propertyNames'),
|
||||
required: require('./required'),
|
||||
uniqueItems: require('./uniqueItems'),
|
||||
validate: require('./validate')
|
||||
};
|
||||
140
electron/node_modules/ajv/lib/dotjs/items.js
generated
vendored
140
electron/node_modules/ajv/lib/dotjs/items.js
generated
vendored
|
|
@ -1,140 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_items(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $idx = 'i' + $lvl,
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$currentBaseId = it.baseId;
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
|
||||
if (Array.isArray($schema)) {
|
||||
var $additionalItems = it.schema.additionalItems;
|
||||
if ($additionalItems === false) {
|
||||
out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
|
||||
var $currErrSchemaPath = $errSchemaPath;
|
||||
$errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
out += ' if (!' + ($valid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } ';
|
||||
$errSchemaPath = $currErrSchemaPath;
|
||||
if ($breakOnError) {
|
||||
$closingBraces += '}';
|
||||
out += ' else { ';
|
||||
}
|
||||
}
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $sch, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$sch = arr1[$i += 1];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
|
||||
var $passData = $data + '[' + $i + ']';
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
|
||||
$it.dataPathArr[$dataNxt] = $i;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
|
||||
$it.schema = $additionalItems;
|
||||
$it.schemaPath = it.schemaPath + '.additionalItems';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (!' + ($nextValid) + ') break; ';
|
||||
}
|
||||
out += ' } } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
} else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (!' + ($nextValid) + ') break; ';
|
||||
}
|
||||
out += ' }';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
80
electron/node_modules/ajv/lib/dotjs/multipleOf.js
generated
vendored
80
electron/node_modules/ajv/lib/dotjs/multipleOf.js
generated
vendored
|
|
@ -1,80 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (!($isData || typeof $schema == 'number')) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
out += 'var division' + ($lvl) + ';if (';
|
||||
if ($isData) {
|
||||
out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
|
||||
}
|
||||
out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
|
||||
if (it.opts.multipleOfPrecision) {
|
||||
out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
|
||||
} else {
|
||||
out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
|
||||
}
|
||||
out += ' ) ';
|
||||
if ($isData) {
|
||||
out += ' ) ';
|
||||
}
|
||||
out += ' ) { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be multiple of ';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue);
|
||||
} else {
|
||||
out += '' + ($schemaValue) + '\'';
|
||||
}
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += '} ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
84
electron/node_modules/ajv/lib/dotjs/not.js
generated
vendored
84
electron/node_modules/ajv/lib/dotjs/not.js
generated
vendored
|
|
@ -1,84 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_not(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
out += ' var ' + ($errs) + ' = errors; ';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
$it.createErrors = false;
|
||||
var $allErrorsOption;
|
||||
if ($it.opts.allErrors) {
|
||||
$allErrorsOption = $it.opts.allErrors;
|
||||
$it.opts.allErrors = false;
|
||||
}
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.createErrors = true;
|
||||
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT be valid\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT be valid\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (false) { ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
73
electron/node_modules/ajv/lib/dotjs/oneOf.js
generated
vendored
73
electron/node_modules/ajv/lib/dotjs/oneOf.js
generated
vendored
|
|
@ -1,73 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_oneOf(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $currentBaseId = $it.baseId,
|
||||
$prevValid = 'prevValid' + $lvl,
|
||||
$passingSchemas = 'passingSchemas' + $lvl;
|
||||
out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $sch, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$sch = arr1[$i += 1];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
} else {
|
||||
out += ' var ' + ($nextValid) + ' = true; ';
|
||||
}
|
||||
if ($i) {
|
||||
out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
|
||||
}
|
||||
}
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should match exactly one schema in oneOf\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; return false; ';
|
||||
}
|
||||
}
|
||||
out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
|
||||
if (it.opts.allErrors) {
|
||||
out += ' } ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
85
electron/node_modules/ajv/lib/dotjs/pattern.js
generated
vendored
85
electron/node_modules/ajv/lib/dotjs/pattern.js
generated
vendored
|
|
@ -1,85 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_pattern(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
|
||||
if ($isData) {
|
||||
out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
|
||||
}
|
||||
out += ' !' + ($valid) + ') {';
|
||||
} else {
|
||||
var $regexp = it.usePattern($schema);
|
||||
out += ' if ( ';
|
||||
if ($isData) {
|
||||
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
|
||||
}
|
||||
out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {';
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
|
||||
if ($isData) {
|
||||
out += '' + ($schemaValue);
|
||||
} else {
|
||||
out += '' + (it.util.toQuotedString($schema));
|
||||
}
|
||||
out += ' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should match pattern "';
|
||||
if ($isData) {
|
||||
out += '\' + ' + ($schemaValue) + ' + \'';
|
||||
} else {
|
||||
out += '' + (it.util.escapeQuotes($schema));
|
||||
}
|
||||
out += '"\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + (it.util.toQuotedString($schema));
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += '} ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
335
electron/node_modules/ajv/lib/dotjs/properties.js
generated
vendored
335
electron/node_modules/ajv/lib/dotjs/properties.js
generated
vendored
|
|
@ -1,335 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_properties(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $key = 'key' + $lvl,
|
||||
$idx = 'idx' + $lvl,
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$dataProperties = 'dataProperties' + $lvl;
|
||||
var $schemaKeys = Object.keys($schema || {}).filter(notProto),
|
||||
$pProperties = it.schema.patternProperties || {},
|
||||
$pPropertyKeys = Object.keys($pProperties).filter(notProto),
|
||||
$aProperties = it.schema.additionalProperties,
|
||||
$someProperties = $schemaKeys.length || $pPropertyKeys.length,
|
||||
$noAdditional = $aProperties === false,
|
||||
$additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
|
||||
$removeAdditional = it.opts.removeAdditional,
|
||||
$checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
|
||||
$ownProperties = it.opts.ownProperties,
|
||||
$currentBaseId = it.baseId;
|
||||
var $required = it.schema.required;
|
||||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
|
||||
var $requiredHash = it.util.toHash($required);
|
||||
}
|
||||
|
||||
function notProto(p) {
|
||||
return p !== '__proto__';
|
||||
}
|
||||
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
|
||||
if ($ownProperties) {
|
||||
out += ' var ' + ($dataProperties) + ' = undefined;';
|
||||
}
|
||||
if ($checkAdditional) {
|
||||
if ($ownProperties) {
|
||||
out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
|
||||
} else {
|
||||
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
|
||||
}
|
||||
if ($someProperties) {
|
||||
out += ' var isAdditional' + ($lvl) + ' = !(false ';
|
||||
if ($schemaKeys.length) {
|
||||
if ($schemaKeys.length > 8) {
|
||||
out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
|
||||
} else {
|
||||
var arr1 = $schemaKeys;
|
||||
if (arr1) {
|
||||
var $propertyKey, i1 = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while (i1 < l1) {
|
||||
$propertyKey = arr1[i1 += 1];
|
||||
out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($pPropertyKeys.length) {
|
||||
var arr2 = $pPropertyKeys;
|
||||
if (arr2) {
|
||||
var $pProperty, $i = -1,
|
||||
l2 = arr2.length - 1;
|
||||
while ($i < l2) {
|
||||
$pProperty = arr2[$i += 1];
|
||||
out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
|
||||
}
|
||||
}
|
||||
}
|
||||
out += ' ); if (isAdditional' + ($lvl) + ') { ';
|
||||
}
|
||||
if ($removeAdditional == 'all') {
|
||||
out += ' delete ' + ($data) + '[' + ($key) + ']; ';
|
||||
} else {
|
||||
var $currentErrorPath = it.errorPath;
|
||||
var $additionalProperty = '\' + ' + $key + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
}
|
||||
if ($noAdditional) {
|
||||
if ($removeAdditional) {
|
||||
out += ' delete ' + ($data) + '[' + ($key) + ']; ';
|
||||
} else {
|
||||
out += ' ' + ($nextValid) + ' = false; ';
|
||||
var $currErrSchemaPath = $errSchemaPath;
|
||||
$errSchemaPath = it.errSchemaPath + '/additionalProperties';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is an invalid additional property';
|
||||
} else {
|
||||
out += 'should NOT have additional properties';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
$errSchemaPath = $currErrSchemaPath;
|
||||
if ($breakOnError) {
|
||||
out += ' break; ';
|
||||
}
|
||||
}
|
||||
} else if ($additionalIsSchema) {
|
||||
if ($removeAdditional == 'failing') {
|
||||
out += ' var ' + ($errs) + ' = errors; ';
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
$it.schema = $aProperties;
|
||||
$it.schemaPath = it.schemaPath + '.additionalProperties';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
|
||||
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
var $passData = $data + '[' + $key + ']';
|
||||
$it.dataPathArr[$dataNxt] = $key;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
} else {
|
||||
$it.schema = $aProperties;
|
||||
$it.schemaPath = it.schemaPath + '.additionalProperties';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
|
||||
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
var $passData = $data + '[' + $key + ']';
|
||||
$it.dataPathArr[$dataNxt] = $key;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (!' + ($nextValid) + ') break; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
it.errorPath = $currentErrorPath;
|
||||
}
|
||||
if ($someProperties) {
|
||||
out += ' } ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
var $useDefaults = it.opts.useDefaults && !it.compositeRule;
|
||||
if ($schemaKeys.length) {
|
||||
var arr3 = $schemaKeys;
|
||||
if (arr3) {
|
||||
var $propertyKey, i3 = -1,
|
||||
l3 = arr3.length - 1;
|
||||
while (i3 < l3) {
|
||||
$propertyKey = arr3[i3 += 1];
|
||||
var $sch = $schema[$propertyKey];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
var $prop = it.util.getProperty($propertyKey),
|
||||
$passData = $data + $prop,
|
||||
$hasDefault = $useDefaults && $sch.default !== undefined;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + $prop;
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
|
||||
$it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
|
||||
$it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
$code = it.util.varReplace($code, $nextData, $passData);
|
||||
var $useData = $passData;
|
||||
} else {
|
||||
var $useData = $nextData;
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
|
||||
}
|
||||
if ($hasDefault) {
|
||||
out += ' ' + ($code) + ' ';
|
||||
} else {
|
||||
if ($requiredHash && $requiredHash[$propertyKey]) {
|
||||
out += ' if ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') { ' + ($nextValid) + ' = false; ';
|
||||
var $currentErrorPath = it.errorPath,
|
||||
$currErrSchemaPath = $errSchemaPath,
|
||||
$missingProperty = it.util.escapeQuotes($propertyKey);
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
$errSchemaPath = it.errSchemaPath + '/required';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
$errSchemaPath = $currErrSchemaPath;
|
||||
it.errorPath = $currentErrorPath;
|
||||
out += ' } else { ';
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') { ' + ($nextValid) + ' = true; } else { ';
|
||||
} else {
|
||||
out += ' if (' + ($useData) + ' !== undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ' ) { ';
|
||||
}
|
||||
}
|
||||
out += ' ' + ($code) + ' } ';
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($pPropertyKeys.length) {
|
||||
var arr4 = $pPropertyKeys;
|
||||
if (arr4) {
|
||||
var $pProperty, i4 = -1,
|
||||
l4 = arr4.length - 1;
|
||||
while (i4 < l4) {
|
||||
$pProperty = arr4[i4 += 1];
|
||||
var $sch = $pProperties[$pProperty];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
|
||||
$it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
|
||||
if ($ownProperties) {
|
||||
out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
|
||||
} else {
|
||||
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
|
||||
}
|
||||
out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
|
||||
var $passData = $data + '[' + $key + ']';
|
||||
$it.dataPathArr[$dataNxt] = $key;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (!' + ($nextValid) + ') break; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else ' + ($nextValid) + ' = true; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
81
electron/node_modules/ajv/lib/dotjs/propertyNames.js
generated
vendored
81
electron/node_modules/ajv/lib/dotjs/propertyNames.js
generated
vendored
|
|
@ -1,81 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $errs = 'errs__' + $lvl;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
out += 'var ' + ($errs) + ' = errors;';
|
||||
if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
var $key = 'key' + $lvl,
|
||||
$idx = 'idx' + $lvl,
|
||||
$i = 'i' + $lvl,
|
||||
$invalidName = '\' + ' + $key + ' + \'',
|
||||
$dataNxt = $it.dataLevel = it.dataLevel + 1,
|
||||
$nextData = 'data' + $dataNxt,
|
||||
$dataProperties = 'dataProperties' + $lvl,
|
||||
$ownProperties = it.opts.ownProperties,
|
||||
$currentBaseId = it.baseId;
|
||||
if ($ownProperties) {
|
||||
out += ' var ' + ($dataProperties) + ' = undefined; ';
|
||||
}
|
||||
if ($ownProperties) {
|
||||
out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
|
||||
} else {
|
||||
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
|
||||
}
|
||||
out += ' var startErrs' + ($lvl) + ' = errors; ';
|
||||
var $passData = $key;
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
if (it.util.varOccurences($code, $nextData) < 2) {
|
||||
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
|
||||
} else {
|
||||
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
|
||||
}
|
||||
it.compositeRule = $it.compositeRule = $wasComposite;
|
||||
out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; } var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; return false; ';
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' break; ';
|
||||
}
|
||||
out += ' } }';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
124
electron/node_modules/ajv/lib/dotjs/ref.js
generated
vendored
124
electron/node_modules/ajv/lib/dotjs/ref.js
generated
vendored
|
|
@ -1,124 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_ref(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $async, $refCode;
|
||||
if ($schema == '#' || $schema == '#/') {
|
||||
if (it.isRoot) {
|
||||
$async = it.async;
|
||||
$refCode = 'validate';
|
||||
} else {
|
||||
$async = it.root.schema.$async === true;
|
||||
$refCode = 'root.refVal[0]';
|
||||
}
|
||||
} else {
|
||||
var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
|
||||
if ($refVal === undefined) {
|
||||
var $message = it.MissingRefError.message(it.baseId, $schema);
|
||||
if (it.opts.missingRefs == 'fail') {
|
||||
it.logger.error($message);
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (false) { ';
|
||||
}
|
||||
} else if (it.opts.missingRefs == 'ignore') {
|
||||
it.logger.warn($message);
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
} else {
|
||||
throw new it.MissingRefError(it.baseId, $schema, $message);
|
||||
}
|
||||
} else if ($refVal.inline) {
|
||||
var $it = it.util.copy(it);
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
$it.schema = $refVal.schema;
|
||||
$it.schemaPath = '';
|
||||
$it.errSchemaPath = $schema;
|
||||
var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
|
||||
out += ' ' + ($code) + ' ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
}
|
||||
} else {
|
||||
$async = $refVal.$async === true || (it.async && $refVal.$async !== false);
|
||||
$refCode = $refVal.code;
|
||||
}
|
||||
}
|
||||
if ($refCode) {
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = '';
|
||||
if (it.opts.passContext) {
|
||||
out += ' ' + ($refCode) + '.call(this, ';
|
||||
} else {
|
||||
out += ' ' + ($refCode) + '( ';
|
||||
}
|
||||
out += ' ' + ($data) + ', (dataPath || \'\')';
|
||||
if (it.errorPath != '""') {
|
||||
out += ' + ' + (it.errorPath);
|
||||
}
|
||||
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
|
||||
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
|
||||
out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) ';
|
||||
var __callValidate = out;
|
||||
out = $$outStack.pop();
|
||||
if ($async) {
|
||||
if (!it.async) throw new Error('async schema referenced by sync schema');
|
||||
if ($breakOnError) {
|
||||
out += ' var ' + ($valid) + '; ';
|
||||
}
|
||||
out += ' try { await ' + (__callValidate) + '; ';
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($valid) + ' = true; ';
|
||||
}
|
||||
out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($valid) + ' = false; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($valid) + ') { ';
|
||||
}
|
||||
} else {
|
||||
out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
270
electron/node_modules/ajv/lib/dotjs/required.js
generated
vendored
270
electron/node_modules/ajv/lib/dotjs/required.js
generated
vendored
|
|
@ -1,270 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_required(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
var $vSchema = 'schema' + $lvl;
|
||||
if (!$isData) {
|
||||
if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
|
||||
var $required = [];
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $property, i1 = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while (i1 < l1) {
|
||||
$property = arr1[i1 += 1];
|
||||
var $propertySch = it.schema.properties[$property];
|
||||
if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
|
||||
$required[$required.length] = $property;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var $required = $schema;
|
||||
}
|
||||
}
|
||||
if ($isData || $required.length) {
|
||||
var $currentErrorPath = it.errorPath,
|
||||
$loopRequired = $isData || $required.length >= it.opts.loopRequired,
|
||||
$ownProperties = it.opts.ownProperties;
|
||||
if ($breakOnError) {
|
||||
out += ' var missing' + ($lvl) + '; ';
|
||||
if ($loopRequired) {
|
||||
if (!$isData) {
|
||||
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
|
||||
}
|
||||
var $i = 'i' + $lvl,
|
||||
$propertyPath = 'schema' + $lvl + '[' + $i + ']',
|
||||
$missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
|
||||
}
|
||||
out += ' var ' + ($valid) + ' = true; ';
|
||||
if ($isData) {
|
||||
out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
|
||||
}
|
||||
out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
|
||||
}
|
||||
out += '; if (!' + ($valid) + ') break; } ';
|
||||
if ($isData) {
|
||||
out += ' } ';
|
||||
}
|
||||
out += ' if (!' + ($valid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } else { ';
|
||||
} else {
|
||||
out += ' if ( ';
|
||||
var arr2 = $required;
|
||||
if (arr2) {
|
||||
var $propertyKey, $i = -1,
|
||||
l2 = arr2.length - 1;
|
||||
while ($i < l2) {
|
||||
$propertyKey = arr2[$i += 1];
|
||||
if ($i) {
|
||||
out += ' || ';
|
||||
}
|
||||
var $prop = it.util.getProperty($propertyKey),
|
||||
$useData = $data + $prop;
|
||||
out += ' ( ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
|
||||
}
|
||||
}
|
||||
out += ') { ';
|
||||
var $propertyPath = 'missing' + $lvl,
|
||||
$missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } else { ';
|
||||
}
|
||||
} else {
|
||||
if ($loopRequired) {
|
||||
if (!$isData) {
|
||||
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
|
||||
}
|
||||
var $i = 'i' + $lvl,
|
||||
$propertyPath = 'schema' + $lvl + '[' + $i + ']',
|
||||
$missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
|
||||
}
|
||||
if ($isData) {
|
||||
out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
|
||||
}
|
||||
out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
|
||||
}
|
||||
out += ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
|
||||
if ($isData) {
|
||||
out += ' } ';
|
||||
}
|
||||
} else {
|
||||
var arr3 = $required;
|
||||
if (arr3) {
|
||||
var $propertyKey, i3 = -1,
|
||||
l3 = arr3.length - 1;
|
||||
while (i3 < l3) {
|
||||
$propertyKey = arr3[i3 += 1];
|
||||
var $prop = it.util.getProperty($propertyKey),
|
||||
$missingProperty = it.util.escapeQuotes($propertyKey),
|
||||
$useData = $data + $prop;
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
out += ' if ( ' + ($useData) + ' === undefined ';
|
||||
if ($ownProperties) {
|
||||
out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
|
||||
}
|
||||
out += ') { var err = '; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
out += 'is a required property';
|
||||
} else {
|
||||
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
it.errorPath = $currentErrorPath;
|
||||
} else if ($breakOnError) {
|
||||
out += ' if (true) {';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
86
electron/node_modules/ajv/lib/dotjs/uniqueItems.js
generated
vendored
86
electron/node_modules/ajv/lib/dotjs/uniqueItems.js
generated
vendored
|
|
@ -1,86 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $isData = it.opts.$data && $schema && $schema.$data,
|
||||
$schemaValue;
|
||||
if ($isData) {
|
||||
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
|
||||
$schemaValue = 'schema' + $lvl;
|
||||
} else {
|
||||
$schemaValue = $schema;
|
||||
}
|
||||
if (($schema || $isData) && it.opts.uniqueItems !== false) {
|
||||
if ($isData) {
|
||||
out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
|
||||
}
|
||||
out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
|
||||
var $itemType = it.schema.items && it.schema.items.type,
|
||||
$typeIsArray = Array.isArray($itemType);
|
||||
if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
|
||||
out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
|
||||
} else {
|
||||
out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
|
||||
var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
|
||||
out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
|
||||
if ($typeIsArray) {
|
||||
out += ' if (typeof item == \'string\') item = \'"\' + item; ';
|
||||
}
|
||||
out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($isData) {
|
||||
out += ' } ';
|
||||
}
|
||||
out += ' if (!' + ($valid) + ') { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: ';
|
||||
if ($isData) {
|
||||
out += 'validate.schema' + ($schemaPath);
|
||||
} else {
|
||||
out += '' + ($schema);
|
||||
}
|
||||
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } ';
|
||||
if ($breakOnError) {
|
||||
out += ' else { ';
|
||||
}
|
||||
} else {
|
||||
if ($breakOnError) {
|
||||
out += ' if (true) { ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
482
electron/node_modules/ajv/lib/dotjs/validate.js
generated
vendored
482
electron/node_modules/ajv/lib/dotjs/validate.js
generated
vendored
|
|
@ -1,482 +0,0 @@
|
|||
'use strict';
|
||||
module.exports = function generate_validate(it, $keyword, $ruleType) {
|
||||
var out = '';
|
||||
var $async = it.schema.$async === true,
|
||||
$refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
|
||||
$id = it.self._getId(it.schema);
|
||||
if (it.opts.strictKeywords) {
|
||||
var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
|
||||
if ($unknownKwd) {
|
||||
var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
|
||||
if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
|
||||
else throw new Error($keywordsMsg);
|
||||
}
|
||||
}
|
||||
if (it.isTop) {
|
||||
out += ' var validate = ';
|
||||
if ($async) {
|
||||
it.async = true;
|
||||
out += 'async ';
|
||||
}
|
||||
out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
|
||||
if ($id && (it.opts.sourceCode || it.opts.processCode)) {
|
||||
out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
|
||||
}
|
||||
}
|
||||
if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
|
||||
var $keyword = 'false schema';
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
if (it.schema === false) {
|
||||
if (it.isTop) {
|
||||
$breakOnError = true;
|
||||
} else {
|
||||
out += ' var ' + ($valid) + ' = false; ';
|
||||
}
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'boolean schema is false\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
} else {
|
||||
if (it.isTop) {
|
||||
if ($async) {
|
||||
out += ' return data; ';
|
||||
} else {
|
||||
out += ' validate.errors = null; return true; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var ' + ($valid) + ' = true; ';
|
||||
}
|
||||
}
|
||||
if (it.isTop) {
|
||||
out += ' }; return validate; ';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (it.isTop) {
|
||||
var $top = it.isTop,
|
||||
$lvl = it.level = 0,
|
||||
$dataLvl = it.dataLevel = 0,
|
||||
$data = 'data';
|
||||
it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
|
||||
it.baseId = it.baseId || it.rootId;
|
||||
delete it.isTop;
|
||||
it.dataPathArr = [""];
|
||||
if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored in the schema root';
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
out += ' var vErrors = null; ';
|
||||
out += ' var errors = 0; ';
|
||||
out += ' if (rootData === undefined) rootData = data; ';
|
||||
} else {
|
||||
var $lvl = it.level,
|
||||
$dataLvl = it.dataLevel,
|
||||
$data = 'data' + ($dataLvl || '');
|
||||
if ($id) it.baseId = it.resolve.url(it.baseId, $id);
|
||||
if ($async && !it.async) throw new Error('async schema in sync schema');
|
||||
out += ' var errs_' + ($lvl) + ' = errors;';
|
||||
}
|
||||
var $valid = 'valid' + $lvl,
|
||||
$breakOnError = !it.opts.allErrors,
|
||||
$closingBraces1 = '',
|
||||
$closingBraces2 = '';
|
||||
var $errorKeyword;
|
||||
var $typeSchema = it.schema.type,
|
||||
$typeIsArray = Array.isArray($typeSchema);
|
||||
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
|
||||
if ($typeIsArray) {
|
||||
if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
|
||||
} else if ($typeSchema != 'null') {
|
||||
$typeSchema = [$typeSchema, 'null'];
|
||||
$typeIsArray = true;
|
||||
}
|
||||
}
|
||||
if ($typeIsArray && $typeSchema.length == 1) {
|
||||
$typeSchema = $typeSchema[0];
|
||||
$typeIsArray = false;
|
||||
}
|
||||
if (it.schema.$ref && $refKeywords) {
|
||||
if (it.opts.extendRefs == 'fail') {
|
||||
throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
|
||||
} else if (it.opts.extendRefs !== true) {
|
||||
$refKeywords = false;
|
||||
it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
|
||||
}
|
||||
}
|
||||
if (it.schema.$comment && it.opts.$comment) {
|
||||
out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
|
||||
}
|
||||
if ($typeSchema) {
|
||||
if (it.opts.coerceTypes) {
|
||||
var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
|
||||
}
|
||||
var $rulesGroup = it.RULES.types[$typeSchema];
|
||||
if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
|
||||
var $schemaPath = it.schemaPath + '.type',
|
||||
$errSchemaPath = it.errSchemaPath + '/type';
|
||||
var $schemaPath = it.schemaPath + '.type',
|
||||
$errSchemaPath = it.errSchemaPath + '/type',
|
||||
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
|
||||
out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
|
||||
if ($coerceToTypes) {
|
||||
var $dataType = 'dataType' + $lvl,
|
||||
$coerced = 'coerced' + $lvl;
|
||||
out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';
|
||||
if (it.opts.coerceTypes == 'array') {
|
||||
out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';
|
||||
}
|
||||
out += ' if (' + ($coerced) + ' !== undefined) ; ';
|
||||
var arr1 = $coerceToTypes;
|
||||
if (arr1) {
|
||||
var $type, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$type = arr1[$i += 1];
|
||||
if ($type == 'string') {
|
||||
out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
|
||||
} else if ($type == 'number' || $type == 'integer') {
|
||||
out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
|
||||
if ($type == 'integer') {
|
||||
out += ' && !(' + ($data) + ' % 1)';
|
||||
}
|
||||
out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
|
||||
} else if ($type == 'boolean') {
|
||||
out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
|
||||
} else if ($type == 'null') {
|
||||
out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
|
||||
} else if (it.opts.coerceTypes == 'array' && $type == 'array') {
|
||||
out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
out += ' else { ';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be ';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } if (' + ($coerced) + ' !== undefined) { ';
|
||||
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
|
||||
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
|
||||
out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
|
||||
if (!$dataLvl) {
|
||||
out += 'if (' + ($parentData) + ' !== undefined)';
|
||||
}
|
||||
out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
|
||||
} else {
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be ';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
}
|
||||
out += ' } ';
|
||||
}
|
||||
}
|
||||
if (it.schema.$ref && !$refKeywords) {
|
||||
out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
|
||||
if ($breakOnError) {
|
||||
out += ' } if (errors === ';
|
||||
if ($top) {
|
||||
out += '0';
|
||||
} else {
|
||||
out += 'errs_' + ($lvl);
|
||||
}
|
||||
out += ') { ';
|
||||
$closingBraces2 += '}';
|
||||
}
|
||||
} else {
|
||||
var arr2 = it.RULES;
|
||||
if (arr2) {
|
||||
var $rulesGroup, i2 = -1,
|
||||
l2 = arr2.length - 1;
|
||||
while (i2 < l2) {
|
||||
$rulesGroup = arr2[i2 += 1];
|
||||
if ($shouldUseGroup($rulesGroup)) {
|
||||
if ($rulesGroup.type) {
|
||||
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
|
||||
}
|
||||
if (it.opts.useDefaults) {
|
||||
if ($rulesGroup.type == 'object' && it.schema.properties) {
|
||||
var $schema = it.schema.properties,
|
||||
$schemaKeys = Object.keys($schema);
|
||||
var arr3 = $schemaKeys;
|
||||
if (arr3) {
|
||||
var $propertyKey, i3 = -1,
|
||||
l3 = arr3.length - 1;
|
||||
while (i3 < l3) {
|
||||
$propertyKey = arr3[i3 += 1];
|
||||
var $sch = $schema[$propertyKey];
|
||||
if ($sch.default !== undefined) {
|
||||
var $passData = $data + it.util.getProperty($propertyKey);
|
||||
if (it.compositeRule) {
|
||||
if (it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored for: ' + $passData;
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
} else {
|
||||
out += ' if (' + ($passData) + ' === undefined ';
|
||||
if (it.opts.useDefaults == 'empty') {
|
||||
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
|
||||
}
|
||||
out += ' ) ' + ($passData) + ' = ';
|
||||
if (it.opts.useDefaults == 'shared') {
|
||||
out += ' ' + (it.useDefault($sch.default)) + ' ';
|
||||
} else {
|
||||
out += ' ' + (JSON.stringify($sch.default)) + ' ';
|
||||
}
|
||||
out += '; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
|
||||
var arr4 = it.schema.items;
|
||||
if (arr4) {
|
||||
var $sch, $i = -1,
|
||||
l4 = arr4.length - 1;
|
||||
while ($i < l4) {
|
||||
$sch = arr4[$i += 1];
|
||||
if ($sch.default !== undefined) {
|
||||
var $passData = $data + '[' + $i + ']';
|
||||
if (it.compositeRule) {
|
||||
if (it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored for: ' + $passData;
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
} else {
|
||||
out += ' if (' + ($passData) + ' === undefined ';
|
||||
if (it.opts.useDefaults == 'empty') {
|
||||
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
|
||||
}
|
||||
out += ' ) ' + ($passData) + ' = ';
|
||||
if (it.opts.useDefaults == 'shared') {
|
||||
out += ' ' + (it.useDefault($sch.default)) + ' ';
|
||||
} else {
|
||||
out += ' ' + (JSON.stringify($sch.default)) + ' ';
|
||||
}
|
||||
out += '; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var arr5 = $rulesGroup.rules;
|
||||
if (arr5) {
|
||||
var $rule, i5 = -1,
|
||||
l5 = arr5.length - 1;
|
||||
while (i5 < l5) {
|
||||
$rule = arr5[i5 += 1];
|
||||
if ($shouldUseRule($rule)) {
|
||||
var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
|
||||
if ($code) {
|
||||
out += ' ' + ($code) + ' ';
|
||||
if ($breakOnError) {
|
||||
$closingBraces1 += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces1) + ' ';
|
||||
$closingBraces1 = '';
|
||||
}
|
||||
if ($rulesGroup.type) {
|
||||
out += ' } ';
|
||||
if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
|
||||
out += ' else { ';
|
||||
var $schemaPath = it.schemaPath + '.type',
|
||||
$errSchemaPath = it.errSchemaPath + '/type';
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = ''; /* istanbul ignore else */
|
||||
if (it.createErrors !== false) {
|
||||
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' } ';
|
||||
if (it.opts.messages !== false) {
|
||||
out += ' , message: \'should be ';
|
||||
if ($typeIsArray) {
|
||||
out += '' + ($typeSchema.join(","));
|
||||
} else {
|
||||
out += '' + ($typeSchema);
|
||||
}
|
||||
out += '\' ';
|
||||
}
|
||||
if (it.opts.verbose) {
|
||||
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
|
||||
}
|
||||
out += ' } ';
|
||||
} else {
|
||||
out += ' {} ';
|
||||
}
|
||||
var __err = out;
|
||||
out = $$outStack.pop();
|
||||
if (!it.compositeRule && $breakOnError) {
|
||||
/* istanbul ignore if */
|
||||
if (it.async) {
|
||||
out += ' throw new ValidationError([' + (__err) + ']); ';
|
||||
} else {
|
||||
out += ' validate.errors = [' + (__err) + ']; return false; ';
|
||||
}
|
||||
} else {
|
||||
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
|
||||
}
|
||||
out += ' } ';
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' if (errors === ';
|
||||
if ($top) {
|
||||
out += '0';
|
||||
} else {
|
||||
out += 'errs_' + ($lvl);
|
||||
}
|
||||
out += ') { ';
|
||||
$closingBraces2 += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
out += ' ' + ($closingBraces2) + ' ';
|
||||
}
|
||||
if ($top) {
|
||||
if ($async) {
|
||||
out += ' if (errors === 0) return data; ';
|
||||
out += ' else throw new ValidationError(vErrors); ';
|
||||
} else {
|
||||
out += ' validate.errors = vErrors; ';
|
||||
out += ' return errors === 0; ';
|
||||
}
|
||||
out += ' }; return validate;';
|
||||
} else {
|
||||
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
|
||||
}
|
||||
|
||||
function $shouldUseGroup($rulesGroup) {
|
||||
var rules = $rulesGroup.rules;
|
||||
for (var i = 0; i < rules.length; i++)
|
||||
if ($shouldUseRule(rules[i])) return true;
|
||||
}
|
||||
|
||||
function $shouldUseRule($rule) {
|
||||
return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
|
||||
}
|
||||
|
||||
function $ruleImplementsSomeKeyword($rule) {
|
||||
var impl = $rule.implements;
|
||||
for (var i = 0; i < impl.length; i++)
|
||||
if (it.schema[impl[i]] !== undefined) return true;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
132
electron/node_modules/ajv/lib/jtd.ts
generated
vendored
Normal file
132
electron/node_modules/ajv/lib/jtd.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import type {AnySchemaObject, SchemaObject, JTDParser} from "./types"
|
||||
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
|
||||
import AjvCore, {CurrentOptions} from "./core"
|
||||
import jtdVocabulary from "./vocabularies/jtd"
|
||||
import jtdMetaSchema from "./refs/jtd-schema"
|
||||
import compileSerializer from "./compile/jtd/serialize"
|
||||
import compileParser from "./compile/jtd/parse"
|
||||
import {SchemaEnv} from "./compile"
|
||||
|
||||
const META_SCHEMA_ID = "JTD-meta-schema"
|
||||
|
||||
type JTDOptions = CurrentOptions & {
|
||||
// strict mode options not supported with JTD:
|
||||
strict?: never
|
||||
allowMatchingProperties?: never
|
||||
allowUnionTypes?: never
|
||||
validateFormats?: never
|
||||
// validation and reporting options not supported with JTD:
|
||||
$data?: never
|
||||
verbose?: boolean
|
||||
$comment?: never
|
||||
formats?: never
|
||||
loadSchema?: never
|
||||
// options to modify validated data:
|
||||
useDefaults?: never
|
||||
coerceTypes?: never
|
||||
// advanced options:
|
||||
next?: never
|
||||
unevaluated?: never
|
||||
dynamicRef?: never
|
||||
meta?: boolean
|
||||
defaultMeta?: never
|
||||
inlineRefs?: boolean
|
||||
loopRequired?: never
|
||||
multipleOfPrecision?: never
|
||||
}
|
||||
|
||||
export 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
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = exports = Ajv
|
||||
module.exports.Ajv = Ajv
|
||||
Object.defineProperty(exports, "__esModule", {value: true})
|
||||
|
||||
export default Ajv
|
||||
|
||||
export {
|
||||
Format,
|
||||
FormatDefinition,
|
||||
AsyncFormatDefinition,
|
||||
KeywordDefinition,
|
||||
KeywordErrorDefinition,
|
||||
CodeKeywordDefinition,
|
||||
MacroKeywordDefinition,
|
||||
FuncKeywordDefinition,
|
||||
Vocabulary,
|
||||
Schema,
|
||||
SchemaObject,
|
||||
AnySchemaObject,
|
||||
AsyncSchema,
|
||||
AnySchema,
|
||||
ValidateFunction,
|
||||
AsyncValidateFunction,
|
||||
ErrorObject,
|
||||
ErrorNoParams,
|
||||
JTDParser,
|
||||
} from "./types"
|
||||
|
||||
export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
|
||||
export {SchemaCxt, SchemaObjCxt} from "./compile"
|
||||
export {KeywordCxt} from "./compile/validate"
|
||||
export {JTDErrorObject} from "./vocabularies/jtd"
|
||||
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
|
||||
|
||||
export {JTDSchemaType, SomeJTDSchemaType, JTDDataType}
|
||||
export {JTDOptions}
|
||||
export {default as ValidationError} from "./runtime/validation_error"
|
||||
export {default as MissingRefError} from "./compile/ref_error"
|
||||
146
electron/node_modules/ajv/lib/keyword.js
generated
vendored
146
electron/node_modules/ajv/lib/keyword.js
generated
vendored
|
|
@ -1,146 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
|
||||
var customRuleCode = require('./dotjs/custom');
|
||||
var definitionSchema = require('./definition_schema');
|
||||
|
||||
module.exports = {
|
||||
add: addKeyword,
|
||||
get: getKeyword,
|
||||
remove: removeKeyword,
|
||||
validate: validateKeyword
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Define custom keyword
|
||||
* @this Ajv
|
||||
* @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
|
||||
* @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addKeyword(keyword, definition) {
|
||||
/* jshint validthis: true */
|
||||
/* eslint no-shadow: 0 */
|
||||
var RULES = this.RULES;
|
||||
if (RULES.keywords[keyword])
|
||||
throw new Error('Keyword ' + keyword + ' is already defined');
|
||||
|
||||
if (!IDENTIFIER.test(keyword))
|
||||
throw new Error('Keyword ' + keyword + ' is not a valid identifier');
|
||||
|
||||
if (definition) {
|
||||
this.validateKeyword(definition, true);
|
||||
|
||||
var dataType = definition.type;
|
||||
if (Array.isArray(dataType)) {
|
||||
for (var i=0; i<dataType.length; i++)
|
||||
_addRule(keyword, dataType[i], definition);
|
||||
} else {
|
||||
_addRule(keyword, dataType, definition);
|
||||
}
|
||||
|
||||
var metaSchema = definition.metaSchema;
|
||||
if (metaSchema) {
|
||||
if (definition.$data && this._opts.$data) {
|
||||
metaSchema = {
|
||||
anyOf: [
|
||||
metaSchema,
|
||||
{ '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
definition.validateSchema = this.compile(metaSchema, true);
|
||||
}
|
||||
}
|
||||
|
||||
RULES.keywords[keyword] = RULES.all[keyword] = true;
|
||||
|
||||
|
||||
function _addRule(keyword, dataType, definition) {
|
||||
var ruleGroup;
|
||||
for (var i=0; i<RULES.length; i++) {
|
||||
var rg = RULES[i];
|
||||
if (rg.type == dataType) {
|
||||
ruleGroup = rg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!ruleGroup) {
|
||||
ruleGroup = { type: dataType, rules: [] };
|
||||
RULES.push(ruleGroup);
|
||||
}
|
||||
|
||||
var rule = {
|
||||
keyword: keyword,
|
||||
definition: definition,
|
||||
custom: true,
|
||||
code: customRuleCode,
|
||||
implements: definition.implements
|
||||
};
|
||||
ruleGroup.rules.push(rule);
|
||||
RULES.custom[keyword] = rule;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get keyword
|
||||
* @this Ajv
|
||||
* @param {String} keyword pre-defined or custom keyword.
|
||||
* @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
|
||||
*/
|
||||
function getKeyword(keyword) {
|
||||
/* jshint validthis: true */
|
||||
var rule = this.RULES.custom[keyword];
|
||||
return rule ? rule.definition : this.RULES.keywords[keyword] || false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove keyword
|
||||
* @this Ajv
|
||||
* @param {String} keyword pre-defined or custom keyword.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function removeKeyword(keyword) {
|
||||
/* jshint validthis: true */
|
||||
var RULES = this.RULES;
|
||||
delete RULES.keywords[keyword];
|
||||
delete RULES.all[keyword];
|
||||
delete RULES.custom[keyword];
|
||||
for (var i=0; i<RULES.length; i++) {
|
||||
var rules = RULES[i].rules;
|
||||
for (var j=0; j<rules.length; j++) {
|
||||
if (rules[j].keyword == keyword) {
|
||||
rules.splice(j, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate keyword definition
|
||||
* @this Ajv
|
||||
* @param {Object} definition keyword definition object.
|
||||
* @param {Boolean} throwError true to throw exception if definition is invalid
|
||||
* @return {boolean} validation result
|
||||
*/
|
||||
function validateKeyword(definition, throwError) {
|
||||
validateKeyword.errors = null;
|
||||
var v = this._validateKeyword = this._validateKeyword
|
||||
|| this.compile(definitionSchema, true);
|
||||
|
||||
if (v(definition)) return true;
|
||||
validateKeyword.errors = v.errors;
|
||||
if (throwError)
|
||||
throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
|
||||
else
|
||||
return false;
|
||||
}
|
||||
26
electron/node_modules/ajv/lib/refs/data.json
generated
vendored
26
electron/node_modules/ajv/lib/refs/data.json
generated
vendored
|
|
@ -1,17 +1,13 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON Schema extension proposal)",
|
||||
"type": "object",
|
||||
"required": [ "$data" ],
|
||||
"properties": {
|
||||
"$data": {
|
||||
"type": "string",
|
||||
"anyOf": [
|
||||
{ "format": "relative-json-pointer" },
|
||||
{ "format": "json-pointer" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
"$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
||||
"description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
|
||||
"type": "object",
|
||||
"required": ["$data"],
|
||||
"properties": {
|
||||
"$data": {
|
||||
"type": "string",
|
||||
"anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
|
|
|
|||
28
electron/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts
generated
vendored
Normal file
28
electron/node_modules/ajv/lib/refs/json-schema-2019-09/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type Ajv from "../../core"
|
||||
import type {AnySchemaObject} from "../../types"
|
||||
import * as metaSchema from "./schema.json"
|
||||
import * as applicator from "./meta/applicator.json"
|
||||
import * as content from "./meta/content.json"
|
||||
import * as core from "./meta/core.json"
|
||||
import * as format from "./meta/format.json"
|
||||
import * as metadata from "./meta/meta-data.json"
|
||||
import * as validation from "./meta/validation.json"
|
||||
|
||||
const META_SUPPORT_DATA = ["/properties"]
|
||||
|
||||
export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv {
|
||||
;[
|
||||
metaSchema,
|
||||
applicator,
|
||||
content,
|
||||
core,
|
||||
with$data(this, format),
|
||||
metadata,
|
||||
with$data(this, validation),
|
||||
].forEach((sch) => this.addMetaSchema(sch, undefined, false))
|
||||
return this
|
||||
|
||||
function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
|
||||
return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue