Giter VIP home page Giter VIP logo

json-schema's People

Contributors

hudlow avatar jdesrosiers 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

json-schema's Issues

Bundling schema with urn ID does not replace urn $ref

Hi,

I'm trying to bundle a schema with urn identifiers.
I added the urn plugin for @hyperjump/browser based on the example.
The external schema (Address) is added to $defs in the resulting schema, but the $ref is not changed to refer to $defs.
What am I doing wrong?

Combining the two following schemas:

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"$id": "urn:test:something/schemas/CompanyCertificate",
	"type": "object",
	"title": "Company Certificate",
	"description": "It's the Company Certificate",
	"properties": {
		"companyInformation": {
			"type": "object",
			"properties": {
				"businessAddress": {
					"$ref": "urn:test:something/schemas/Address"
				}
			}
		}
	}
}
{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"$id": "urn:test:something/schemas/Address",
	"type": "object",
	"required": ["addressLine1", "postalCode", "postalPlace"],
	"properties": {
		"addressLine1": {
			"type": "string"
		},
		"postalCode": {
			"type": "string"
		},
		"postalPlace": {
			"type": "string"
		}
	}
}

With this code:

addUriSchemePlugin("urn", {
  parse: (urn, baseUri) => {
    let { nid, nss, query, fragment } = parseUrn(urn);
    nid = nid.toLowerCase();

    if (!mappings[nid]?.[nss]) {
      throw Error(`Not Found -- ${urn}`);
    }

    let uri = mappings[nid][nss];
    uri += query ? `?${query}` : "";
    uri += fragment ? `#${fragment}` : "";

    return retrieve(uri, baseUri);
  },
});

registerSchema(schema);
registerSchema(Address);

const bundledSchema = await bundle(
  "urn:test:something/schemas/CompanyCertificate"
);

Results in this:

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"type": "object",
	"title": "Company Certificate",
	"description": "It's the Company Certificate",
	"properties": {
		"companyInformation": {
			"type": "object",
			"properties": {
				"businessAddress": { "$ref": "urn:test:something/schemas/Address" }
			}
		}
	},
	"$defs": {
		"Address": {
			"$id": "Address",
			"type": "object",
			"required": ["addressLine1", "postalCode", "postalPlace"],
			"properties": {
				"addressLine1": { "type": "string" },
				"postalCode": { "type": "string" },
				"postalPlace": { "type": "string" }
			}
		}
	}
}

Thanks!

Error: Encountered unknown dialect https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1

Info

Details

  • validator.ts
const schemaId = "https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1";
const luggageSchemaId = "https://schemas.amazon.com/selling-partners/definitions/product-types/schema/v1/SHIRT";
const metaSchemaPath = "./src/functions/SP-API/Schemes/MetaSchemes/amazon-product-type-definition-meta-schema-v1.json";
const luggageSchemaPath = "./src/functions/SP-API/Schemes/productSchemes/SHIRT.json";
const customVocabularyId = "https://schemas.amazon.com/selling-partners/definitions/product-types/vocabulary/v1";

export async function validator(payload:any) {
  defineVocabulary(schemaId,{
    vocabularyToken: "$vocabulary"
  })
  const customKeywords = {
    maxUniqueItems : maxUniqueItemsKeyword as any,
    minUtf8ByteLength : minUtf8ByteLengthKeyword as any,
    maxUtf8ByteLength : maxUtf8ByteLengthKeyword as any
  };
  defineVocabulary(customVocabularyId, customKeywords);
  const metaSchemaJSON = JSON.parse(fs.readFileSync(metaSchemaPath,"utf8"));
// loadDialect(schemaId, {})
  addSchema(metaSchemaJSON, schemaId); // Error: Encountered unknown dialect 'https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1'
  const luggageSchemaJSON = JSON.parse(fs.readFileSync(luggageSchemaPath, "utf8"));
  addSchema(luggageSchemaJSON, luggageSchemaId, schemaId);
  const result = await validate(luggageSchemaId, payload, BASIC) // Error: Encountered unknown keyword '$id' at https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1#
  return result
}
  • metaSchemaPath(amazon-product-type-definition-meta-schema-v1.json)
{
  "$schema": "https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1",
  "$id": "https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1",
  // etc...
}

Question

I encountered the following error:
Error: Encountered unknown dialect 'https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1'

I thought that this dialect was not set correctly, so I added the following code:
loadDialect(schemaId, {})
However, now I encounter this error:
Encountered unknown keyword '$id' at https://schemas.amazon.com/selling-partners/definitions/product-types/meta-schema/v1#

I have been stuck on this for quite some time. Could you provide any advice?

uniqueItems in object leads to TypeError

On https://json-schema.hyperjump.io/ enter the schema:

{
  "$schema": "https://json-schema.org/draft/2019-09/schema#",
  "type": "object",
  "properties": {
    "test": {
      "type": "object",
      "uniqueItems": true
   }
  }
}

The schema is declared Valid although uniqueItems is only expected for arrays. This is in line with other validators. Now enter a simple instance:

{
  "test": {
  }
}

This results in TypeError: se(...).map is not a function

The problem would also occur on top-level. I used object "test" to illustrate that it only occurs when there is an instance of the object with uniqueItems attribute.

Typescript error while importing from `@hyperjump/json-schema/experimental`

When building I get this error:

error TS2307: Cannot find module '@hyperjump/json-schema/experimental' or its corresponding type declarations.

Reproduction:

git clone https://github.com/GabenGar/repros
cd ./repros/json-schema-experimental-module
npm install
npm run build

It is an issue with type definitions because vanilla js file works fine.

Beginner issue: load schema from file and bundle into one

Please help me out.

I have two schemas S1.json and defs.json which are only local and cannot be fetched via https.

They are properly declared with $id

S1 contains business entities, $defs and $ref to defs.json
defs.json only contains $defs and $ref to #

I am under the impression, that this tool can help me to bundle into one schema.json, yet for me without javascript knowledge, I do not know where to start.

I guess I have to write a tiny program and execute with npx, correct?
I start from the sample https://github.com/hyperjump-io/json-schema#bundling

  • How can I load a local file?
  • How is it supposed to work out that $id in defs.json is the one $ref in S1 are referring to? Do I need a mapping between https://unavailble.schema in defs.json is actually a local file instead to be fetched from the internet?
  • How can I save the bundle result to a final file?

Thank you for your support!

.schema.json file is not recognized by media type system

Running on a MacBook, this simple TypeScript program:

import { compile } from '@hyperjump/json-schema/experimental';
import path from 'path';

async function main(): Promise<void> {
  const fullPath = path.resolve('./test.schema.json');

  const compiledSchema = await compile(`file://${fullPath}`);

  console.log(JSON.stringify(compiledSchema, undefined, 2));
}

main()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    console.log(error);
    process.exit(-1);
  });

Produces this error:

Error: file:///Users/hgilliam/git/assure/assure-libs/workspaces/@quil-libs/assure-firestore-data/v2-codegen/test.schema.json is not a schema. Found a document with media type: application/octet-stream

Despite the README stating that when reading from the filesystem a file with the .schema.json suffix would be correctly recognized as a schema file.

Using version 1.2.1 of the package.

Possible to expose option to configure http-cache?

Howdy. Attempting to use this validator in an AWS Lambda env causes issues with attempts to write to disk. I believe the cause is in json-schema-core's usage of the "make-fetch-happen" library, where it codes as follows:

const fetch = makeFetchHappen.defaults({ cacheManager: "./http-cache" });

It would be excellent if the local location of this cache (and the option to disable it completely) would be exposed as configurable quantities in your lib. Love it otherwise!

window system

@hyperjump/[email protected] postinstall E:\Project\code\ui\enterprise\node_modules@hyperjump\json-pointer
rm -rf dist

'rm' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

Does not consider schema valid if top level `$ref`

Hyperjump does not consider the following schema as valid.

{
  "$ref": "#/definitions/Coords",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Coords": {
      "type": "object",
      "properties": {
        "lat": { "type": "number" },
        "long": { "type": "number" }
      },
      "required": ["lat", "long"]
    }
  }
}

It shows the following error:
Hyperjump - JSON Schema Validator

Other validators consider it valid and can use it to validate other JSON documents.

JSON Schema Lint __ JSON Schema Validator

Screenshot 2023-09-20 at 12 30 37 PM

JsonType missing "integer" as an allowed value

Currently the definition of JsonType is as follows: https://github.com/hyperjump-io/json-schema-core/blob/c808bedbb80e90b649b263c92c38df23a32e87bb/lib/common.d.ts#L1

I've haven't read all the specs, but draft-07 and 2020-12 have identical definitions for "type":

String values MUST be one of the six primitive types ("null",
"boolean", "object", "array", "number", or "string"), or "integer"
which matches any number with a zero fractional part.

It appears "integer" is missing from the definitions.

Links to the specifications:

Documentation and package.json should list minimum Node version as 16

This package will not work with Node14 for example because it uses FileHandle.createReadStream, which doesn't exists in Node14. Adding the minimum Node version to the docs and listing in the engines config in package.json will save people a lot of headache wondering why things fail out of the box when using versions pre-16

Validation for invalid OpenAPI 3.1.0 document returns an empty `errors` array

Issue is as stated above, I passed in my OpenAPI 3.1.0 document to the validate method that was shown in the main README.md.

import { validate } from "@hyperjump/json-schema/openapi-3-1";
import fs from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));

const openapi = JSON.parse(fs.readFileSync(join(__dirname, "openapi3.1.json")));

try {
  // Validate an OpenAPI document
  const output = await validate(
    "https://spec.openapis.org/oas/3.1/schema-base",
    openapi
  );
  console.log(output);
} catch (err) {
  console.log(err);
}

Below is the output

{
  keyword: 'https://json-schema.org/evaluation/validate',
  absoluteKeywordLocation: 'https://spec.openapis.org/oas/3.1/schema-base/2022-10-07#',
  instanceLocation: '#',
  valid: false,
  errors: []
}

Expected output:
If my OpenAPI document is not valid, I expected to receive errors that specified what issues I need to resolve.

Actual output:
An invalid OpenAPI 3.1.0 document returns an empty errors array

TypeScript type definitions are broken

This TS code will not build:

import path from 'path';
import { readFileSync } from 'node:fs';
import { addSchema } from '@hyperjump/json-schema/draft-2020-12';
import { compile } from '@hyperjump/json-schema/experimental';

async function main(): Promise<void> {
  const fullPath = path.resolve('./test.schema.json');

  const schema = JSON.parse(readFromFile(fullPath));

  addSchema(schema, 'https://example.com/test.schema.json');

  const compiledSchema = await compile('https://example.com/test.schema.json');

  console.log(JSON.stringify(compiledSchema, undefined, 2));
}

function readFromFile(filename: string): string {
  return readFileSync(filename, { encoding: 'utf8' });
}

main()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    console.log(error);
    process.exit(-1);
  });

It produces the errors:

> tsc

node_modules/@hyperjump/json-schema/lib/invalid-schema-error.d.ts:1:15 - error TS2305: Module '"./core.js"' has no exported member 'Result'.

1 import type { Result } from "./core.js";
                ~~~~~~

node_modules/@hyperjump/json-schema/lib/media-types.d.ts:7:21 - error TS2304: Cannot find name 'Response'.

7   parse: (response: Response, mediaTypeParameters: { [parameter: string]: string }) => Promise<[SchemaObject, string | undefined]>;
                      ~~~~~~~~


Found 2 errors in 2 files.

Errors  Files
     1  node_modules/@hyperjump/json-schema/lib/invalid-schema-error.d.ts:1
     1  node_modules/@hyperjump/json-schema/lib/media-types.d.ts:7

README / API section copy and pasted description

In the API section two methods have the same description (apart from the word "See"), which looks incorrect.

API

  • validate: (schema: SDoc, instance: any, outputFormat: OutputFormat = FLAG) => OutputUnit

    Validate an instance against a schema. The function is curried to allow
    compiling the schema once and applying it to multiple instances. See

  • setMetaOutputFormat: (outputFormat: OutputFormat) => undefined

    Validate an instance against a schema. The function is curried to allow
    compiling the schema once and applying it to multiple instances.

Comparisons to other validator implementations

Just as a suggestion, would you consider adding some info about how JSV differentiates itself from other JS-based jsonschema validators like AJV? A full benchmark comparison is not necessary, but would be helpful for visitors to get an idea of what the primary goals of the project are- for example performance? portability? coverage all jsonschema draft versions? Really great project so far btw.

Regular expression parsing failure

"valueDecimal": {
"description": "The actual value to for an initial answer.",
"pattern": "^-?(0|[1-9][0-9]{0,17})(\\.[0-9]{1,17})?([eE][+-]?[0-9]{1,9}})?$",
"type": "number"
}

validate fails with: SyntaxError: Invalid regular expression: /^-?(0|[1-9][0-9]{0,17})(.[0-9]{1,17})?([eE][+-]?[0-9]{1,9}})?$/: Lone quantifier brackets at new RegExp ()

YAML support

Hi! Any chance of supporting YAML validations of a json schema?

Adding formats

JSON schema defines a few built-in formats for the format keyword, but as far as I can tell, none work with this module. Would it be possible to add a addFormat function to define such formats, for example:

addFormat("email", str => emailRe.test(str));

How to make a schema from inline?

I really can't figure out how to just import a schema that's defined inline. How do I load a simple schema and then execute it using this library without using abolute paths or host it online?

const JsonSchema = require("@hyperjump/json-schema");

const sch = JSON.parse(`{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://somesite.com/schema/base",
    "type": "object",
    "title": "This is the outer doc",
    "properties": {
        "version": { "type": "string" },
        "info": { "$ref": "/schema/info" }
    },
    "required": ["version", "info"],
    "$defs": {
        "info": {
            "$id": "/schema/info",
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "type": "object",
            "properties": {
                "issuer": { "type": "string" }
            },
            "required": ["issuer"]
        }
    }
}`)

const input = {
    "version": "test",
    "info": { "issuer": "test" },
}

JsonSchema.validate(sch, input).then(console.log).catch(console.error)

Invalid JSON schema has passed check

https://json-schema.hyperjump.io/

schema

{
  "$id": "https://json-schema.hyperjump.io/schema",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$defs": {
    "Foo": {
      "Bar": {
        "type": "boolean"
      }
    }
  },
  "$ref": "#/$defs/Foo/Bar"
}

instance

true
image

All check passed


But see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00

The "$defs" keyword reserves a location for schema authors to inline
re-usable JSON Schemas into a more general schema. The keyword does
not directly affect the validation result.

This keyword's value MUST be an object. Each member value of this
object MUST be a valid JSON Schema.

But the object { "Bar": { "type": "boolean" } } not seems to be a valid JSON Schema.

How can I get errors for all instanceLocation?

Let's consider the following schema

{
    "$id": "https://example.com/user-data",
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "properties": {
      "name": { "type": "string", "default": "Unknown" },
      "email": { 
		"type": "string", 
		"format": "email",
	},
      "tags": {
        	"type": "array",
       		"minItems": 3,
        	"items": { "type": "string", "minLength": 2 }
      },
      "score": { "type": "integer", "minimum": 0 },
      "date": { "type": "integer", "format": "unix-time" },
			"nospace": {
				"pattern": "^\\S*$",
				"type": "string"
			},
			"extra": {
				"anyOf": [
				{
					"type": "string"
				},
				{
					"type": "null"
				}
			]
		}
    },
    "required": ["name", "email", "tags", "score", "extra"],
  }

I am getting errors only for tags property for the following json

{
    "name": "Unknown",
    "email": "",
    "tags": [],
    "score": -50,
    "extra": 123
  }

Schema validation using discriminator mapping seems to fail

Online tool shows that the JSON payload below is valid for the given JSON Schema.

My expectation is the discriminator criterion will indicate the payload for SINGLE_SELECT will contain a required value property.

When validated, the SINGLE_SELECT criterion is recognized as valid JSON, even though the value property is not present.

JSON

{
  "name": "search-1",
  "criteria": [
    {
      "categoryId": "roadClass",
      "criterion": "SINGLE_SELECT"
    }
  ]
}

Schema

$schema: "https://json-schema.org/draft/2020-12/schema"

type: object
properties:
  name: 
    type: string
  criteria:
    type: array
    items: 
      $ref: '#/components/schemas/SearchCriterion'

components:
  schemas:
    SearchCriterion:
      type: object

      properties:
        categoryId:
          type: string
          description: The category being queried
        criterion:
          $ref: '#/components/schemas/SearchCriterionEnum'

      required:
        - categoryId
        - criterion

      discriminator:
        propertyName: criterion
        mapping:
          SINGLE_SELECT: '#/components/schemas/SearchCriterionSingleSelect'

    SearchCriterionEnum:
      description: List of the different types of supported search criteria

      type: string

      enum:
        - PARTIAL_TEXT
        - NUMERIC_RANGE
        - SINGLE_SELECT
        - MULTI_SELECT
        - BOOLEAN

    SearchCriterionSingleSelect:
      description: |
        Returns true if the compared value matches the chosen value.
      allOf:
        - $ref: '#/components/schemas/SearchCriterion'
        - type: object
          properties:
            value:
              type: string
            temporal:
              $ref: '#/components/schemas/SearchCriterionTemporal'
          required:
            - value

Cannot use validation in background scripts/service workers of browser extensions

Hi,

I would like to use your library in the context of a browser extension for Chrome/Firefox built using the Web Extensions API.

The main logic of the extension is run in a so-called background script. In Manifest V3 versions of that API these are executed using service workers. The main impact is of course that we do not have a reference to the DOM and the document global variable is undefined.

When running the following code in this context I unfortunately get an exception because it assumes a normal web browser context:

const BOOKMARK_SCHEMA_URI = 'https://raw.githubusercontent.com/frederikb/bookmarksync/main/src/utils/bookmark.schema.json';
registerSchema(bookmarkSchema); // this is a parsed JSON containing the schema with a `$id` defined matching the uri
const validator = await validate(BOOKMARK_SCHEMA_URI);

The error:

ReferenceError: document is not defined
at contextUri (background.js:13617:46)
at get (background.js:13620:69)
at getSchema (background.js:13701:26)
at validate

The stacktrace is a bit mangled due to not having source maps set up, but the gist of it is that it's failing in @hyperjump/browser:

export const contextUri = () => document.location.toString();

while attempting to determine baseUri because it assumes a browser context.

My schema does not have any references to external schemas, neither absolute nor relative to.

  1. Is running in a web/service worker supposed to work and I'm doing some wrong?
  2. If not, is this something you are interested in supporting?
  3. Is there a workaround you would suggest? I could probably stub out the global document, but with what kind of location?

Thanks!

Doesn't adhere to the draft4 official test suite with regards to minLength and unicode

This validator seems to be failing this test: https://github.com/json-schema-org/JSON-Schema-Test-Suite/blob/dfcea626f1bb442008dc7f5183a002c398f6601c/tests/draft4/minLength.json#L27-L29.

As a runnable example:

const JsonSchema = require("@hyperjump/json-schema");

const schemaJson = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://example.com/schemas/test",
  "minLength": 2
};

JsonSchema.add(schemaJson);

(async () => {
  const schema = await JsonSchema.get("http://example.com/schemas/test");
  const output = await JsonSchema.validate(schema, "\uD83D\uDCA9");
  console.log(output)
})()

Not working for YAML schema's.

I did as instructed adding a YAML mediaTypePlugin:

import { validate, addMediaTypePlugin } from '@hyperjump/json-schema/openapi-3-0'
import { pathToFileURL } from 'node:url'
import { join } from 'node:path'
import { load } from 'js-yaml'

const is31 = RegExp.prototype.test.bind(/^3\.1\.\d+(-.+)?$/)
const is30 = RegExp.prototype.test.bind(/^3\.0\.\d+(-.+)?$/)

addMediaTypePlugin("application/yaml", {
  parse: async (response, contentTypeParameters) => {
    const doc = load(await response.text());

    let defaultDialect;
    const version = doc.openapi || contentTypeParameters.version;

    if (!version) {
      throw Error("Invalid OpenAPI document. Add the 'openapi' field and try again.");
    } else if (is30(version)) {
      defaultDialect = "https://spec.openapis.org/oas/3.0/schema";
    } else if (is31(version)) {
      if (!("jsonSchemaDialect" in doc) || doc.jsonSchemaDialect === "https://spec.openapis.org/oas/3.1/dialect/base") {
        defaultDialect = "https://spec.openapis.org/oas/3.1/schema-base";
      } else {
        defaultDialect = `https://spec.openapis.org/oas/3.1/schema-${encodeURIComponent(doc.jsonSchemaDialect)}`;
      }
    } else {
      throw Error(`Encountered unsupported OpenAPI version '${version}' in ${response.url}`);
    }

    return [doc, defaultDialect];
  },
  matcher: (path) => /\.ya*ml$/.test(path)
});

const validSchema = await validate(pathToFileURL(join('doc', 'openapi_spec.yaml')))

But it always fails with

/node_modules/@hyperjump/json-schema/lib/schema.js:26
throw Error(Encountered unknown dialect '${dialectId}');

Also, manually navigating to all the default dialects are Github 404's..

When the defaultDialect is hardcoded to undefined as in the README example, it always throws. No idea why it even tries querying https://json-schema.org/validation

node_modules/@hyperjump/json-schema/lib/schema.js:172
      throw Error(`Failed to retrieve ${id} (${response.status} ${response.statusText})`);
            ^

Error: Failed to retrieve https://json-schema.org/validation (404 Not Found)
    at get (file:///C:/Users/johndoe/project/node_modules/@hyperjump/json-schema/lib/schema.js:172:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Module.get (file:///C:/Users/johndoe/project/node_modules/@hyperjump/json-schema/lib/schema.js:180:7)
    at async compile (file:///C:/Users/johndoe/project/node_modules/@hyperjump/json-schema/lib/core.js:27:18)
    at async validate (file:///C:/Users/johndoe/project/node_modules/@hyperjump/json-schema/lib/core.js:20:20)
    at async file:///C:/Users/johndoe/project/test.js:36:21

TypeError: Cannot read properties of undefined (reading 'match')

async function run(){
    console.log('\n\n<------------------------------ Starting\n')
   
    const
        JsonSchema = require("@hyperjump/json-schema"),
        schemaJson = {
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "$id": "http://example.com/schemas/string",
            "type": "string"
        }

        
    const output = await JsonSchema.validate(schemaJson, "foo");

    console.log(output)
}

run()

Produces output:

<------------------------------ Starting

C:\path\to\jsonschema\node_modules\uri-js\dist\es5\uri.all.js:874
    var matches = uriString.match(URI_PARSE);
                            ^

TypeError: Cannot read properties of undefined (reading 'match')
    at parse (C:\path\to\jsonschema\node_modules\uri-js\dist\es5\uri.all.js:874:29)
    at Object.resolve (C:\path\to\jsonschema\node_modules\uri-js\dist\es5\uri.all.js:1124:75)
    at resolveUrl (C:\path\to\jsonschema\node_modules\@hyperjump\json-schema-core\lib\common.js:17:27)  
    at Object.get (C:\path\to\jsonschema\node_modules\@hyperjump\json-schema-core\lib\schema.js:193:23) 
    at compileSchema (C:\path\to\jsonschema\node_modules\@hyperjump\json-schema-core\lib\core.js:112:37)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async compile (C:\path\to\jsonschema\node_modules\@hyperjump\json-schema-core\lib\core.js:33:21)
    at async Object.validate (C:\path\to\jsonschema\node_modules\@hyperjump\json-schema-core\lib\core.js:25:20)
    at async run (C:\path\to\jsonschema\index.js:14:20)

With the following package.json:

{
  "name": "y",
  "version": "1.0.0",
  "description": "JSONSchema experiment",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "@hyperjump/json-schema": "^0.23.3"
  }
}

bug: prefixItems schema does not evaluate

The following schema does not produce an error as expected where idddd is an additional property. Is this a bug or is my schema wrong?

{
    "$id": "https://www.freecodecamp.org/classroom/userDataRequest",
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "title": "UserDataRequest",
    "description": "Queries a collection of users and certifications",
    "users": {
        "type": "array",
        "uniqueItems": true,
        "prefixItems": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        },
        "items": {
            "description": "name of the certification block",
            "type": "string",
            "pattern": "^[A-Za-z][\/A-Za-z0-9-]*[A-Za-z]$"
        }
    },
    "required": ["users"]
}
{
  "users": [
    {
      "idddd": "123456"
    },
    "2022/responsive-web-design",
    "quality-assurance"
  ]
}

[Help Wanted] How can I get descriptive error messages when the schema is invalid.

I have the following schema

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "array",
    "items": {
        "type": "string"
    }
}

and following data

[1,2,3]

Now when I validate the schema, the I get the following error

{"keyword":"https://json-schema.org/keyword/items","absoluteKeywordLocation":"http://example.com/schemas/string#/items","instanceLocation":"#","valid":false,
"errors":[{"keyword":"https://json-schema.org/evaluation/validate","absoluteKeywordLocation":"http://example.com/schemas/string#/items","instanceLocation":"#/0","valid":false,
"errors":[{"keyword":"https://json-schema.org/keyword/type","absoluteKeywordLocation":"http://example.com/schemas/string#/items/type","instanceLocation":"#/0","valid":false,"errors":[]}]}]}

My code

image

What I am looking for is a descriptive error similar to what cfworker/json-schema throws

Items did not match schema. Instance type "number" is invalid. Expected "string".

Enable fetch options to be customised.

We're loading schemas over the network which are protected by authentication and we need the ability to customise the request that's made.

I propose a solution where users can implement a callback, say:

type FetchInitOverrider = (init: RequestInit) => RequestInit

And a function to configure it:

let fetchInitOverrider: FetchInitOverrider | undefined = undefined;

export const setFetchInitOverrider => (fn: FetchInitOverrider): void => {
  fetchInitOverrider = fn
}

Then when a URI is fetched, we check for the overrider and call it if present.

Thoughts?

Issues with media types

I'm trying to bundle a schema that I'm working on. I started with this code:

import { bundle } from "@hyperjump/json-schema/bundle";
const bundledSchema = await bundle(
  "https://schema.kitten-science.com/working-draft/settings-profile.schema.json",
);

This produces:

Error: https://schema.kitten-science.com/working-draft/settings-profile.schema.json is not a schema. Found a document with media type: application/schema+json

This is because the application/schema+json media type is defined in the index of this package, which I don't import here. I have to enforce running that code by running the index:

import "@hyperjump/json-schema";
import { bundle } from "@hyperjump/json-schema/bundle";
const bundledSchema = await bundle(
  "https://schema.kitten-science.com/working-draft/settings-profile.schema.json",
);

When I run that, I then get:

Error: https://json-schema.org/draft-07/schema is not a schema. Found a document with media type: application/octet-stream

What's the idea here? I certainly can't make json-schema.org change how they deliver their schemas. If this media type check is incompatible with json-schema.org, why does it even exist? I would assume the JSON Schema specs have to be loaded every time.

`just-curry-it` is not a declared dependency of `@hyperjump/json-schema` in latest version

https://github.com/hyperjump-io/json-schema/blob/0cef4969ef475ce6877eb6da4052e480fa144f2f/lib/schema.js#LL1C35-L1C35

While transpiling with Parcel, I found that while Pact declares the dependnecy on just-curry-it, this downstream package does not.

🚨 Build failed.

@parcel/core: Failed to resolve 'just-curry-it' from 
'/home/vovgiobt/nodevenv/public_html/blog-backend.cyberscientist.ca/14/lib/node_modules/@hyperjump/json-schema/lib/schema.js'

  /home/vovgiobt/nodevenv/public_html/blog-backend.cyberscientist.ca/14/lib/node_modules/@hyperjump/json-schema/lib/schema.js:1:19
  > 1 | import curry from "just-curry-it";
  >   |                   ^^^^^^^^^^^^^^^
    2 | import * as Pact from "@hyperjump/pact";
    3 | import { nil as nilPointer, append as pointerAppend, get as pointerGet } from "@hyperjump/json-pointer";

@parcel/resolver-default: External dependency "just-curry-it" is not declared in package.json.

  /home/vovgiobt/nodevenv/public_html/blog-backend.cyberscientist.ca/14/lib/node_modules/@hyperjump/json-schema/package.json:37:3
    36 |   "bundleDependencies": false,
  > 37 |   "dependencies": {
  >    |   ^^^^^^^^^^^^^^
    38 |     "@hyperjump/json-pointer": "^1.0.0",
    39 |     "@hyperjump/pact": "^0.2.4",

  💡 Add "just-curry-it" as a dependency.

Possible issue validating JSON Schema instances against metaschemas

Forgive me if I'm doing something wrong here.

I've got json-schema working fine for validating arbitrary JSON instances against a schema. In my case the instances are OAS documents and the schema is the published OAS 3.0 schema.

When I try to validate the published OAS schema as the instance, using the JSON Schema metaschema as the schema, I get the following error:-

TypeError: Cannot read property 'compile' of undefined
      at compileSchema (/home/mike/node/openapi-specification/node_modules/@hyperjump/json-schema-core/lib/core.js:122:55)
      at compileSchema (/home/mike/node/openapi-specification/node_modules/@hyperjump/json-schema-core/lib/core.js:110:35)
      at process._tickCallback (internal/process/next_tick.js:68:7)
      at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
      at startup (internal/bootstrap/node.js:283:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

If I change any character in the id value of the metaschema so it doesn't collide with the actual id of the published metaschema, the error goes away and both positive and negative validations work correctly.

Annotations fail to properly decode pointers

The following code produces an error:

import { registerSchema } from "@hyperjump/json-schema/draft-2020-12";
import { annotate } from "@hyperjump/json-schema/annotations/experimental";

const schemaId = "https://fabc10a6-e699-415c-b5e2-25702695a939.example.hudlow.org";

const schema = {
  $schema: "https://json-schema.org/draft/2020-12/schema",
  $id: schemaId,
  properties: {
    paths: {
      properties: {
        "/pets/{id}": {
          title: "path",
          properties: {
            get: {}
          }
        }
      }
    }
  }
};

registerSchema(schema);

const instance = await annotate(schemaId, {
  paths: {
    "/pets/{id}": {
      get: {}
    }
  }
});
json-schema-sandbox $ node ./test-draft-2020-12.js
file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:149
    throw TypeError(`Value at '${cursor}' is undefined and does not have property '${segment}'`);
          ^

TypeError: Value at '/paths/~1pets~1%7Bid%7D' is undefined and does not have property 'get'
    at applySegment (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:149:11)
    at _get (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:45:30)
    at _get (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:45:12)
    at _get (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:45:12)
    at fn (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:36:27)
    at get (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/node_modules/@hyperjump/json-pointer/lib/index.js:37:39)
    at Module.get (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/lib/instance.js:24:12)
    at Object.<anonymous> (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/annotations/index.js:41:28)
    at publish (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/lib/pubsub.js:23:57)
    at Object.interpret (file:///Volumes/Projects/github.com/hyperjump-io/json-schema/lib/keywords/validation.js:66:13)

Node.js v18.17.1

The reason is that the JSON pointers for the instance location of an annotation are not properly URI-decoded. Consider the the above schema will produce this annotations value:

{
  "/paths/~1pets~1%7Bid%7D": { "https://json-schema.org/keyword/title": [ "path" ] }
}

But this is wrong — because this annotations object is not keyed by a relative pointer URI, but rather by the fragment value from a relative pointer URI, it should be:

{
  "/paths/~1pets~1{id}": { "https://json-schema.org/keyword/title": [ "path" ] }
}

This mismatched logic produces the error, but the annotations are actually themselves wrong.

Error: Encountered unknown dialect 'https://json-schema.org/validation'

Info

NodeJS - 16.20.0 (I know, more on that later)
json-schema - 1.5.1
NextJS - 13.4.19

Repro

This branch basically: https://github.com/GabenGar/todos/tree/unknown-dialect

git clone https://github.com/GabenGar/todos --branch unknown-dialect --single-branch
cd todos
npm run install-all
npm run build

And then get several Error: Encountered unknown dialect 'https://json-schema.org/validation' errors (I assume per worker) during page rendering stage.

Details

I know I don't meet the minimal nodejs req, but I've read all discussions and it looks like it's only due to fetch becoming global in it. And I assume the error is caused by the package trying to fetch something and failing for whatever reason.
However I assumed by following these steps:

I'd avoid any network calls at all.

But it crashing at build step (when no validator functions are called/created) means it crashes at init() function. I assumed by importing from "@hyperjump/json-schema/draft-2020-12" I'd get all parts already. What do I have to do to prevent the package from doing any network/fs calls and instead crash outright when not finding something?

Always tries to fetch from web

When I use this example code (modified from the readme):

import { addSchema } from "@hyperjump/json-schema/draft-2020-12";
import { bundle } from "@hyperjump/json-schema/bundle";
import * as yaml from 'yaml'

addSchema({
  "$id": "https://schema.datum.microntech.io/main",
  "$schema": "https://json-schema.org/draft/2020-12/schema",

  "type": "object",
  "properties": {
    "foo": { "$ref": "/string" }
  }
});

addSchema({
  "$id": "https://schema.datum.microntech.io/string",
  "$schema": "https://json-schema.org/draft/2020-12/schema",

  "type": "string"
});

const bundledSchema = await bundle("https://schema.datum.microntech.io/main"); // {
//   "$id": "https://schema.datum.microntech.io/main",
//   "$schema": "https://json-schema.org/draft/2020-12/schema",
//
//   "type": "object",
//   "properties": {
//     "foo": { "$ref": "/string" }
//   },
//
//   "$defs": {
//     "https://schema.datum.microntech.io/string": {
//       "$id": "https://schema.datum.microntech.io/string",
//       "type": "string"
//     }
//   }
// }

console.log(yaml.stringify(bundledSchema))

Then everything works as expected and I get output.

When I try any other code that uses my own schema files, which I have verified are being added to the schemaStore by the right IDs, then I always get an error that the url cannot be found.

Is there something special I need to do to make this work without having an actual domain name that hosts the files? Why would it work with two example schema but not with 50 real ones?

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.