Code Monkey home page Code Monkey logo

djv's Introduction

Hi there I'm Alex πŸ‘‹

I'm a software engineer for the last 15 years. I admire and practice self-development and craftsmanship, exploring technologies, coding open source and enterprise projects, teaching, speaking and writing about programming πŸ‘‹ ⚽️ πŸ§‘β€πŸ’» 🎧

  • I play JavaScript, Node.js, TypeScript, Go, Git, Docker, Java, Ruby, Kubernetes πŸ”­
  • My interests are around Architecture, Microservices, MicroFrontEnds, DevOps, JSON Schema, Web Components, Algorithms 🌱
  • I write articles on Medium πŸ“
  • Ask me about anything on AlexKorzhikov Twitter πŸ“«
  • We're talking XTechnology πŸ’¬

djv's People

Contributors

0xflotus avatar gitter-badger avatar kgkma avatar korzio avatar openself avatar rgnfln avatar roobingood avatar segphault avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

djv's Issues

Refactoring - Change internal state

For resolving internal references it is used a stack of states, and it adds a state each time function goes into recursion. To find appropriate context, validator creates an object. This should be optimized at least to create a state only if necessary.

  • Refactor state stack mechanism.

Optimization - Avoid empty functions

Some generated functions have an empty body.

// schema
{"integer":{"type":"integer"},"refToInteger":{"$ref":"#/integer"}}
// or
{"default":0}

// generated
function f0(data){"use strict";}"
  • Figure it out 1 schema, is it an error?!
  • Avoid empty functions generation, use inline expression

Avoid using this in API

For addFormat (?!), setErrorHandler and other functions it is possible to specify methods, which can modify internal state of the validator or templater. That should be avoided by specifying only schema, errors and other variables only be accessible. So,

  • make this inaccessible,
  • make schema, errors (already), data accessible,
  • ...

Refactor the state

  • Document current architecture
  • Document state resolution examples from json-schema benchmark
  • Document new state algorithm
  • Implement new state algorithm
  • Include $id support for draft-06

Optimization - Improve escape strategy to avoid escape for non-escape properties

Now

Given a schema with properties with no-escape symbols
When validate function is called with instance
Then the escape strategy adds decode/encode calls
Then the unnecessary calls are made during the runtime
tpl(if (${tpl.data}.hasOwnProperty(decodeURIComponent("${encodeURIComponent(propertyKey)}"))) {);

Should be

Given a schema with properties with no-escape symbols
When validate function is called with instance
Then the escape strategy doesn't add decode/encode calls
Then the unnecessary calls are not made during the runtime

Example

// schema
const jsonSchema = {
  common: {
    properties: {
      type: {
        enum: ['common']
      }
    },
    required: [
      'type'
    ]
  }
};

// test
it('should return undefined if object is valid', () => {
  const env = djv();
  env.addSchema('test', jsonSchema);

  const commonObj = {
    type: 'common'
  };
  const errors = env.validate('test#/common', commonObj);
  assert.equal(errors, undefined);
});

// generated function
if (data !== null && typeof data === 'object' && !Array.isArray(data)) {
  if (!data.hasOwnProperty(decodeURIComponent("type"))) return {
    keyword: 'required',
    dataPath: decodeURIComponent(""),
    schemaPath: decodeURIComponent("#/required")
  };
}
if (data[decodeURIComponent('type')] != decodeURIComponent('common')) return {
  keyword: 'enum',
  dataPath: decodeURIComponent("'type'"),
  schemaPath: decodeURIComponent("#'type'/enum")
};
}

Implement draft-06 changes

  • -1. Add draft-06 tests

  • 0. Use $schema keyword to identify the version of a used specification and use separate specification keywords for different schema versions

  • 1. Check and change if necesarry if boolean values could be a valid schema

Boolean values are equivalent to the following behaviors:
Β true Always passes validation, as if the empty schema {} | Β 
Β false Always fails validation, as if the schema { "not":{} }

  • 2. Optionally check for $schema in the root, and warn about presence in subschemas

The "$schema" keyword SHOULD be used in a root schema. It MUST NOT appear in subschemas.

  • 3. Use $id instead of id

9.2. The "$id" keyword

  • 4. Check other keywords

all core keywords prefixed with "$"

The value of this keyword MUST be a valid JSON Schema.
An array instance is valid against "contains" if at least one of its

If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema. Note the property name that the schema is testing will always be a string.

The value of this keyword MAY be of any type, including null. An instance validates successfully against this keyword if its value is equal to the value of the keyword.

  • 9. Add examples keyword validation (warning)

The value of this keyword MUST be an array. There are no restrictions placed on the values within the array.

Allow empty "required" and "dependencies" arrays

  • 14. Check and fix change if necessary

Fixed "type" reference to primitive types

#17

Release 1.1.0

  • Check speed metrics
  • Check with updated json-schema test suite
  • Create a changelog
  • Update Readme
  • Publish test npm version 1.1.0-alpha.0, check package internals
  • Tag 1.1.0
  • Publish version 1.1.0
  • Send update to gitter

Improve error reporting

Hey. Firstly, great job. I'm working on an application analytics abstraction framework project for some of the UK's largest retailers dealing with very heavy traffic to their sites. I'm in need of a schema validation framework as part of it and application bundle size really matters. Various schema validators I've assessed add 100kb+ to the overall, optimised (usually Webpack based) application size (such as ajv and joi), which just isn't feasible. Whereas yours adds only 11kb optimised, which is fantastic πŸ‘

The only issue I've run into is with error output, or lack of. Unless I'm missing something, it's difficult to really take advantage of validation and error reporting with errors as plain as required: data. Is there currently a way to have more informative and machine dissectible errors? I.e. exactly what fields are missing? Also, the option to halt on first error or error on all?

If not, I'm more than happy to get stuck in and contribute (rather than hound you for features). Plus, through my choice some rather large companies may have a dependency on this library so it's in my own interest to help with its longevity πŸ˜›

Error messages does not really make any sense

Please do not do same error messages as ajv did, they are not really helpful.
I'm moving away from ajv cause it's hard to understand the problem based just on error message. You have to check the source code to get useful info. And whats harder is to create user-friendly error messages. I guess with ajv it's not really possible.

I tested your library, I decide to modify a home page example, simply pass empty object to validation function:

const env = new djv();
const jsonSchema = {
  "common": {
    "properties": {
      "type": {
        "enum": ["common"]
      }
    },
    "required": [
      "type"
    ]
  }
};

// Use `addSchema` to add json-schema
env.addSchema('test', jsonSchema);
env.validate('test#/common', {});

I got in return:

{ keyword: 'required', dataPath: '', schemaPath: '#/required' }

With does not really useful - there is no actual name of the field which is required, which means it's not possible to build user-friendly error either.

But your library looks much easier and flexible then ajv, hope you will fix this issue!

Release 2.1.3

Release 2.1.3

To release a package to npm follow the steps

  • Create a release ticket in github. Copy this checklist.
  • Make a release branch
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git add .
git commit -m "release: Update package version to $VERSIONALPHA #$ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git add .
git commit -m "release: Update package version to $VERSION #$ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter

Fix failing tests draft-04/06, update schema usage

Given a draft-04/06 meta schema update
When running unit tests
Then 17? tests are failing

ebdrup/json-schema-benchmark#37

  • Understand the meta schema changes
  • Use schema from git repository. Now the schema is taken from npm dependency, and it's not updated anymore
  • Fix failing djv tests

Links:

Test branch:


Most tests are failing because of \\ in the schema ids

SyntaxError: Invalid or unexpected token
    at new Function (<anonymous>)
    at restore (/Developer/schema/djv/lib/utils/template.js:124:15)
    at generate (/Developer/schema/djv/lib/utils/state.js:50:10)
    at Environment.addSchema (/Developer/schema/djv/lib/djv.js:90:11)
    at Object.validate (/Developer/schema/djv/test/json-schema-test-suite.js:23:13)
    at doTest (/Developer/schema/djv/node_modules/json-schema-test/index.js:79:43)
    at UserContext.<anonymous> (/Developer/schema/djv/node_modules/json-schema-test/index.js:66:30)
    at attempt (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4478:46)
    at QueueRunner.run (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4402:20)
    at QueueRunner.execute (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4384:10)
result: false
expected:  true
errors: [ 'Invalid or unexpected token' ]
FSyntaxError: Invalid or unexpected token
    at new Function (<anonymous>)
    at restore (/Developer/schema/djv/lib/utils/template.js:124:15)
    at generate (/Developer/schema/djv/lib/utils/state.js:50:10)
    at Environment.addSchema (/Developer/schema/djv/lib/djv.js:90:11)
    at Object.validate (/Developer/schema/djv/test/json-schema-test-suite.js:23:13)
    at doTest (/Developer/schema/djv/node_modules/json-schema-test/index.js:79:43)
    at UserContext.<anonymous> (/Developer/schema/djv/node_modules/json-schema-test/index.js:66:30)
    at attempt (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4478:46)
    at QueueRunner.run (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4402:20)
    at QueueRunner.execute (/Developer/schema/djv/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:4384:10)

Release 2.1.0

  • Create a release ticket in github. Copy this checklist.
  • Make a release branch
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git commit -m "release: Update package version to $VERSIONALPHA #$ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git commit -m "release: Update package version to $VERSION #$ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter

Module entry point

Hey @korzio,

Thanks for the latest release.

We've noticed when optimising a build for production and running everything through UglifyJS (this is a Webpack based build) that UglifyJS throws and error because it is coming across ES6 code in djv, which it of course doesn't understand.

Currently, I'm having to transpile it to ES5 explicitly in my project - https://github.com/operation-orange/analytics-datalayer/blob/master/webpack.config.js#L37

It looks like this is because you are pointing to ./lib/djv.js in your package.json file which is the raw ES6 src. Should it now be pointing to your already transpiled ./djv.js file?

Thanks :)

Release 2.1.2

  • Create a release ticket in github. Copy this checklist.
  • Make a release branch
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git add .
git commit -m "release: Update package version to $VERSIONALPHA #$ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git add .
git commit -m "release: Update package version to $VERSION #$ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter

Add concatenation to built version

As a "frontend" djv user I want to
My built djv package uses a single anonymous function

module.exports = {  
  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin()
  ]
};
  • Update to webpack 3
  • Add a ModuleConcatenationPlugin
  • Add a npm prepublish hook to built everything before a package is actually published
  • Add sourceMaps for an uglified version

POC: Add template forEach function and change it to forEach implementation

As a djv validator developer
I want to have a template forEach function to easily construct cicles for validator functions

Example:
Instead of

tpl('for ($1; $2 < $3.length; $2++) {', tpl.cache('0'), tpl.cache('0'), tpl.data);
  tpl.data.push(`[${tpl.cache('0')}]`);

  const condition = `...`;
  const error = `...`;

  tpl(`if (${condition}) ${error}`, tpl.data);
  tpl.data.pop();

I want smth like

tpl.forEach(tpl.data, () => condition, () => error) // or even map

Coercion

Hi, thanks for writing this library! I like the cleanliness of the code and it appears to be wicked fast πŸ”₯

Have you thought about adding type coercion? It's the only thing keeping me from switching from my current validator. I'd be willing to collaborate on this if it's something you think makes sense in the library.

Feature - Support draft05, draft06

  • Document required changes for draft-05 as a new issue
  • Document required changes for draft-06 as a new issue
  • Make a issue for implementing changes
  • Implement changes. Make tests work
  • Change description to support draft-06 in json-schema-benchmark

Release 1.1.1

  • Create a relese ticket in github. Copy this checklist.
  • Make a release branch
VERSION="1.1.1"
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="35"

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git commit -m "release: Update package version to $VERSIONALPHA #ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git commit -m "release: Update package version to $VERSION #ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag 1.1.1
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version 1.1.1
npm publish
  • Send update to gitter

Optimize function generation

  • Functions used inside the generated function can be executed on addSchema step, not inside the function body. So, update generate function for premature inner helpers functions definition.

Release 1.2.0

  • Create a release ticket in github. Copy this checklist.
  • Remove TODOs
  • Make a release branch
  • Document new state algorithm
  • Add const docs
  • Update Readme (supports draft-06)
  • Add docs to npm ignore
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git commit -m "release: Update package version to $VERSIONALPHA #ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git commit -m "release: Update package version to $VERSION #ISSUE"
  • Create a changelog
npm run changelog
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter
  • Update json-schema supports draft-06 description

POC: Inline generated functions

When generator creates a new function for schema it uses internal private functions for schemas used inside. This functions are declared in a output function body. Inlining those functions should make validator much faster.

Add semver example

With a following schema

{
    type: 'object',
    properties: {
        major: { type: 'integer' },
        minor: { type: 'integer' },
        patch: { type: 'integer' },
        prerelease: { type: 'array', "items": { "$ref": "#/prerelease" } },
        meta: { pattern: '^[0-9A-Za-z-]+$' }
    },
    prerelease: { pattern: '^(?:0[a-zA-Z]*|[a-zA-Z1-9][0-9A-Za-z-]*)$' }
}

Custom error handler has a strange behaviour

Hello. Thanks for the cool package.
I am probably not understanding something, but the customErrorHandler reports everything not just errrors. Example:

const errors = [];
const env = new djv({
  errorHandler(type, tpl, m) {
    errors.push({
      type,
      schema: this.schema[this.schema.length - 1],
      data: this.data[this.data.length - 1]
    });
    return `;`;
  }
});

env.addSchema('default', {
  type: 'object',
  properties: { 
    foo: { type: 'integer' }, 
    boo: { type: 'string' } ,
    moo: { type: 'object', properties: { goo: 'string' }, required: ['goo'] }
  },
  required: ['boo', 'moo']
});

env.validate('default', { foo: 1, boo: '2' })

This reports:

[ { type: 'required', schema: 'schema', data: 'data' },
  { type: 'required', schema: 'schema', data: 'data' },
  { type: 'type', schema: 'schema', data: 'data' },
  { type: 'type', schema: 'schema', data: '[\'foo\']' },
  { type: 'type', schema: 'schema', data: '[\'boo\']' },
  { type: 'required', schema: 'schema', data: '[\'moo\']' },
  { type: 'type', schema: 'schema', data: '[\'moo\']' } ]

Why is all that reported when, foo and boo are obviously correct?
Thanks.

Explain example

I don't understand the example in the readme after trying for an hour or so

Using an example from the JSON schema docs:

http://json-schema.org/example1.html

        const env = new Djv({ version: 'draft-06' })
        const jsonSchema = {
          '$schema': 'http://json-schema.org/draft-06/schema#',
          'title': 'Product',
          'description': 'A product from Acme\'s catalog',
          'type': 'object',
          'properties': {
            'id': {
              'description': 'The unique identifier for a product',
              'type': 'integer'
            },
            'name': {
              'description': 'Name of the product',
              'type': 'string'
            },
            'price': {
              'type': 'number',
              'exclusiveMinimum': 0
            }
          },
          'required': ['id', 'name', 'price']
        }

        const product = {
          'id': 'asdf', // Should be number
          'name': 'A green door',
          'price': 12.50
        }

        // Use `addSchema` to add json schema
        env.addSchema('test', jsonSchema)

        console.log(env.validate('test', product))

Outputs: type: data['id']

This error message makes no sense to me. What is it telling me? How do I parse this so I can show an error message?

It would be better to say "property id is invalid" or whatever. Or return an object with the invalid fields.

{'errors': {
'id': { 'message': 'Field is invalid' }
}}

Release 2.0.0

  • Update documentation for draft-06 support
  • Remove environment update solution - make draft-06 default, add draft-04 configuration optional package
  • Create a release ticket in github. Copy this checklist.
  • Make a release branch
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git commit -m "release: Update package version to $VERSIONALPHA #$ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git commit -m "release: Update package version to $VERSION #ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter

Improvement - Normalize utils

  • Update utils with mirroring concept - now they are using fn() ? invalid: valid, should be vice versa
  • Move utils to separate package?!

json-pointers appear to be irrelevant

Add a schema by name:

env.addSchema('test', jsonSchema);

Validate dataObj against entire schema:

env.validate('test', dataObj);

Validate dataProperty of dataObj against json-pointer ref of schema:

env.validate('test#/dataProperty', { dataProperty: dataObj.dataProperty });

But results as if this was called:

env.validate('test', { dataProperty: dataObj.dataProperty });

Checking what is referenced via resolve:

env.resolve('test');
env.resolve('test#/dataProperty');

results in the identical output.

Single property validation against what should be the correct reference results in validating a partial object against the entire schema. This takes djv from being something lightweight and very useful, to being completely unusable.

djv version: 1.2.0 (root minified file)

POC: Add template if function and collapse multiple consequent cases

  • Check jsperf or other resource that optimization makes sense
  • Add template if function
  • Replace all validators related if-cases
  • Collapse multiple cases, include empty if statements

Possible Syntax

tpl.if('test')
...
tpl.endif() // ?
// => 
'if(test) {}'

Generated function code example

if(a > b) {
  if (c > d) {
    ...
  }
} 
// =>
if(a > b && c > d) {
  ...
}

...
if(a>b){ } 
// =>
// empty

Release 2.1.1

  • Create a release ticket in github. Copy this checklist.
  • Make a release branch
VERSION="..."
VERSIONALPHA="$VERSION-alpha.0"
ISSUE="..."

git checkout -b release/$VERSION
  • Update package.json version to $VERSIONALPHA and commit
git commit -m "release: Update package version to $VERSIONALPHA #$ISSUE"
  • Tag with the alpha version
git tag $VERSIONALPHA
  • Publish test npm version $VERSIONALPHA
npm publish
  • Check package internals - contains all required files (lib/, README.md, ./djv.js, package.json, ...), no extra files
  • Check with updated json-schema test suite - check generated report
  • Check speed metrics
  • Update package.json version to $VERSION and commit
git commit -m "release: Update package version to $VERSION #$ISSUE"
  • Create a changelog
npm run changelog
  • Update Readme
  • Tag $VERSION
git tag $VERSION
  • Merge release branch to master (via github)
  • Publish version $VERSION
npm publish
  • Send update to gitter

Fix JSON-schema-validators suite failing tests

JSON-schema-validators test suite report

test failed reason
a schema given for items, JavaScript pseudo-array is valid Expected result: true but validator returned: false
an array of schemas for items, incomplete array of items Expected result: true but validator returned: false
an array of schemas for items, empty array Expected result: true but validator returned: false
an array of schemas for items, JavaScript pseudo-array is valid Expected result: true but validator returned: false
ECMA 262 regex non-compliance, ECMA 262 has no support for \Z anchor from .NET Expected result: false but validator returned: true
validation of URIs, an invalid protocol-relative URI Reference Expected result: false but validator returned: true
some languages do not distinguish between different types of numeric value, a float is not an integer even without fractional part Expected result: false but validator returned: true
ref overrides any sibling keywords, ref valid, maxItems ignored Expected result: true but validator returned: false
Recursive references between schemas, valid tree The schema failed to load(Cannot read property 'schema' of undefined)
Recursive references between schemas, invalid tree The schema failed to load(Cannot read property 'schema' of undefined)
base URI change - change folder, number is valid The schema failed to load(Cannot read property 'schema' of undefined)
base URI change - change folder, string is invalid The schema failed to load(Cannot read property 'schema' of undefined)
base URI change - change folder in subschema, number is valid The schema failed to load(Cannot read property 'schema' of undefined)
base URI change - change folder in subschema, string is invalid The schema failed to load(Cannot read property 'schema' of undefined)
root ref in remote ref, string is valid The schema failed to load(Cannot read property 'schema' of undefined)
root ref in remote ref, null is valid The schema failed to load(Cannot read property 'schema' of undefined)
root ref in remote ref, object is invalid The schema failed to load(Cannot read property 'schema' of undefined)
required validation, ignores non-objects Expected result: true but validator returned: false

Add invalid keys properties support

  • Schemas with properties containing wrong JavaScript key names (abc-def) fail to generate

Example
{ "config": { "type": "object", "properties": { "abc-def": { "type": "object", "properties": { "key": { "type": "string" }, "url": { "type": "string" }, "required": ["key", "url"] } } }, "required": ["abc-def"] }, "text": { "type": "string" } }

ReferenceError: def is not defined

  • Variables names with quotes, aka properties '%%%%' throw error

Fix additionalProperties on nested schemas

When a schema is nested (not on a first level),
When the iteration of properties uses an expression

tpl(`if(%s.properties.hasOwnProperty(${property})) continue;`, tpl.schema);

Then a schema is taken from the context of the generated validation function,
Then it is a single start point schema.
When additoonalProperties is used on a nested level
Then it will fail to validate

Example @see utils/index:makeSchema.js

return {
    properties: required.reduce((memo, key) => (
      Object.assign({}, memo, {
        [key]: makeSchema(instance[key])
      })
    ), {}),
    required,
    // other properties should be valid by `false` schema, aka not exist at all
    // additionalProperties: false,
  };

uncomment additionalProperties -> error

Required validator throws on null values

Description
When a definition of type object specifies required properties, passing in null to the validate method throws a TypeError: Cannot read property 'hasOwnProperty' of null.

Steps to reproduce

const schema = {
  def: {
    type: 'object',
    properties: {
      foo: { type: 'string' }
    },
    required: ['foo'],
  },
};
const env = djv();
env.addSchema('test', schema);

const obj = null;
const errors = env.validate('test#/def', obj); // should return the errors object

Expected behaviour
The validation fails and errors is populated with the validation error.

Actual behaviour
TypeError: Cannot read property 'hasOwnProperty' of null is thrown.

Version
2.1.1

Stack overflow error

Test case

var djv = require("djv")

var env = djv();

env.addSchema('test', {
    "$schema": "http://json-schema.org/schema#",
    "title": "Aspect capturing a complete representation of a distribution according to Project Open Data (data.json).",
    "type": "object",
    "allOf": [
      {
        "$ref": "https://project-open-data.cio.gov/v1.1/schema/distribution.json"
      }
    ]
  })
  
env.validate('test#', {
    "@type": "dcat:Distribution",
    "downloadURL": "dataset-url/dataset.csv",
    "mediaType": "text/csv"
});

Defect - TypeError: Cannot read property 'schema' of undefined

Doing a quick test to see if I can use djv to validate Swagger 2.0.

Using [email protected]:

Here is the sample script:

var djv = require("djv");
var fs = require("fs");

var JSONSchemaDraftV4 = JSON.parse(fs.readFileSync("./json-schema-draft-v4.json"));
var Swagger2 = JSON.parse(fs.readFileSync("./swagger2.json"));


var env = new djv();
env.addSchema("json-schema-draft-v4", JSONSchemaDraftV4);
env.addSchema("swagger2", Swagger2);

env.validate('swagger2', {});

Here is the output when running it:

$ node test.js 
/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/utils.js:156
        currentSchema = state[uri].schema;
                                  ^

TypeError: Cannot read property 'schema' of undefined
    at Object.resolve (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/utils.js:156:35)
    at Function.resolve (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/generate.js:15:35)
    at $ref (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/validators/$ref.js:6:20)
    at /opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/generate.js:83:53
    at Array.forEach (native)
    at Function.visit (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/generate.js:82:15)
    at properties (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/validators/properties.js:18:12)
    at /opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/generate.js:83:53
    at Array.forEach (native)
    at Function.visit (/opt/node-v6.9.5-linux-x64/lib/node_modules/djv/lib/generate.js:82:15)

Files used in script:

swagger2.json
json-schema-draft-v4.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.