Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor codemeta validation code #43

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions cypress/integration/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ describe('Person validation', function() {
);
cy.get('#validateCodemeta').click();

cy.get('#errorMessage').should('have.text', 'Unknown field "foo" in "author".');
cy.get('#errorMessage').should('have.text', 'Unknown field "foo".');
});

it('errors on Person with invalid field', function() {
Expand Down Expand Up @@ -857,7 +857,7 @@ describe('Organization validation', function() {
);
cy.get('#validateCodemeta').click();

cy.get('#errorMessage').should('have.text', 'Unknown field "foo" in "author".');
cy.get('#errorMessage').should('have.text', 'Unknown field "foo".');
});

it('errors on Organization with invalid field', function() {
Expand Down Expand Up @@ -1005,7 +1005,7 @@ describe('CreativeWork validation', function() {
);
cy.get('#validateCodemeta').click();

cy.get('#errorMessage').should('have.text', 'Unknown field "foo" in "isPartOf".');
cy.get('#errorMessage').should('have.text', 'Unknown field "foo".');
});

it('errors on CreativeWork with invalid field', function() {
Expand Down
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<script src="./js/fields_data.js"></script>
<script src="./js/dynamic_form.js"></script>
<script src="./js/codemeta_generation.js"></script>
<script src="./js/validation/utils.js"></script>
<script src="./js/validation/primitives.js"></script>
<script src="./js/validation/things.js"></script>
<script src="./js/validation/index.js"></script>
Expand Down
16 changes: 9 additions & 7 deletions js/codemeta_generation.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

"use strict";

const LOCAL_CONTEXT_PATH = "./data/contexts/codemeta-local.jsonld";
const LOCAL_CONTEXT_URL = "local";
const INTERNAL_CONTEXT_PATH = "./data/contexts/codemeta-local.jsonld";
const INTERNAL_CONTEXT_URL = "internal";
const CODEMETA_CONTEXTS = {
"2.0": {
path: "./data/contexts/codemeta-2.0.jsonld",
Expand All @@ -25,12 +25,12 @@ const SPDX_PREFIX = 'https://spdx.org/licenses/';
const loadContextData = async () => {
const [contextLocal, contextV2, contextV3] =
await Promise.all([
fetch(LOCAL_CONTEXT_PATH).then(response => response.json()),
fetch(INTERNAL_CONTEXT_PATH).then(response => response.json()),
fetch(CODEMETA_CONTEXTS["2.0"].path).then(response => response.json()),
fetch(CODEMETA_CONTEXTS["3.0"].path).then(response => response.json())
]);
return {
[LOCAL_CONTEXT_URL]: contextLocal,
[INTERNAL_CONTEXT_URL]: contextLocal,
[CODEMETA_CONTEXTS["2.0"].url]: contextV2,
[CODEMETA_CONTEXTS["3.0"].url]: contextV3
}
Expand Down Expand Up @@ -219,7 +219,7 @@ function generateReview() {

async function buildExpandedJson() {
var doc = {
"@context": LOCAL_CONTEXT_URL,
"@context": INTERNAL_CONTEXT_URL,
"@type": "SoftwareSourceCode",
};

Expand Down Expand Up @@ -272,10 +272,11 @@ async function buildExpandedJson() {
async function generateCodemeta(codemetaVersion = "2.0") {
var inputForm = document.querySelector('#inputForm');
var codemetaText, errorHTML;
let compacted;

if (inputForm.checkValidity()) {
const expanded = await buildExpandedJson();
const compacted = await jsonld.compact(expanded, CODEMETA_CONTEXTS[codemetaVersion].url);
compacted = await jsonld.compact(expanded, CODEMETA_CONTEXTS[codemetaVersion].url);
codemetaText = JSON.stringify(compacted, null, 4);
errorHTML = "";
}
Expand All @@ -293,7 +294,8 @@ async function generateCodemeta(codemetaVersion = "2.0") {
// If this finds a validation, it means there is a bug in our code (either
// generation or validation), and the generation MUST NOT generate an
// invalid codemeta file, regardless of user input.
if (codemetaText && !validateDocument(JSON.parse(codemetaText))) {
const isValid = codemetaText && (await parseAndValidateCodemeta(false));
if (!isValid) {
alert('Bug detected! The data you wrote is correct; but for some reason, it seems we generated an invalid codemeta.json. Please report this bug at https://github.com/codemeta/codemeta-generator/issues/new and copy-paste the generated codemeta.json file. Thanks!');
}

Expand Down
234 changes: 196 additions & 38 deletions js/validation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,179 @@
* that are easy to understand for users with no understanding of JSON-LD.
*/

const softwareFieldValidators = {
"@id": validateUrl,
"id": validateUrl,

function validateDocument(doc) {
if (!Array.isArray(doc) && typeof doc != 'object') {
"codeRepository": validateUrls,
"programmingLanguage": noValidation,
"runtimePlatform": validateTexts,
"targetProduct": noValidation, // TODO: validate SoftwareApplication
"applicationCategory": validateTextsOrUrls,
"applicationSubCategory": validateTextsOrUrls,
"downloadUrl": validateUrls,
"fileSize": validateText, // TODO
"installUrl": validateUrls,
"memoryRequirements": validateTextsOrUrls,
"operatingSystem": validateTexts,
"permissions": validateTexts,
"processorRequirements": validateTexts,
"releaseNotes": validateTextsOrUrls,
"softwareHelp": validateCreativeWorks,
"softwareRequirements": noValidation, // TODO: validate SoftwareSourceCode
"softwareVersion": validateText, // TODO?
"storageRequirements": validateTextsOrUrls,
"supportingData": noValidation, // TODO
"author": validateActors,
"citation": validateCreativeWorks, // TODO
"contributor": validateActors,
"copyrightHolder": validateActors,
"copyrightYear": validateNumbers,
"creator": validateActors, // TODO: still in codemeta 2.0, but removed from master
"dateCreated": validateDate,
"dateModified": validateDate,
"datePublished": validateDate,
"editor": validatePersons,
"encoding": noValidation,
"fileFormat": validateTextsOrUrls,
"funder": validateActors, // TODO: may be other types
"keywords": validateTexts,
"license": validateCreativeWorks,
"producer": validateActors,
"provider": validateActors,
"publisher": validateActors,
"sponsor": validateActors,
"version": validateNumberOrText,
"isAccessibleForFree": validateBoolean,
"isSourceCodeOf": validateTextsOrUrls,
"isPartOf": validateCreativeWorks,
"hasPart": validateCreativeWorks,
"position": noValidation,
"identifier": noValidation, // TODO
"description": validateText,
"name": validateText,
"sameAs": validateUrls,
"url": validateUrls,
"relatedLink": validateUrls,
"review": validateReview,

"softwareSuggestions": noValidation, // TODO: validate SoftwareSourceCode
"maintainer": validateActors,
"contIntegration": validateUrls,
"continuousIntegration": validateUrls,
"buildInstructions": validateUrls,
"developmentStatus": validateText, // TODO: use only repostatus strings?
"embargoDate": validateDate,
"embargoEndDate": validateDate,
"funding": validateText,
"issueTracker": validateUrls,
"referencePublication": noValidation, // TODO?
"readme": validateUrls,
};

const creativeWorkFieldValidators = {
"@id": validateUrl,
"id": validateUrl,

"author": validateActors,
"citation": validateCreativeWorks, // TODO
"contributor": validateActors,
"copyrightHolder": validateActors,
"copyrightYear": validateNumbers,
"creator": validateActors, // TODO: still in codemeta 2.0, but removed from master
"dateCreated": validateDate,
"dateModified": validateDate,
"datePublished": validateDate,
"editor": validatePersons,
"encoding": noValidation,
"funder": validateActors, // TODO: may be other types
"keywords": validateTexts,
"license": validateCreativeWorks,
"producer": validateActors,
"provider": validateActors,
"publisher": validateActors,
"sponsor": validateActors,
"version": validateNumberOrText,
"isAccessibleForFree": validateBoolean,
"isPartOf": validateCreativeWorks,
"hasPart": validateCreativeWorks,
"position": noValidation,
"identifier": noValidation, // TODO
"description": validateText,
"name": validateText,
"sameAs": validateUrls,
"url": validateUrls,
};

const roleFieldValidators = {
"roleName": validateText,
"startDate": validateDate,
"endDate": validateDate,

"schema:author": validateActor
};

const personFieldValidators = {
"@id": validateUrl,
"id": validateUrl,

"givenName": validateText,
"familyName": validateText,
"email": validateText,
"affiliation": validateOrganizations,
"identifier": validateUrls,
"name": validateText, // TODO: this is technically valid, but should be allowed here?
"url": validateUrls,
};

const organizationFieldValidators = {
"@id": validateUrl,
"id": validateUrl,

"email": validateText,
"identifier": validateUrls,
"name": validateText,
"address": validateText,
"sponsor": validateActors,
"funder": validateActors, // TODO: may be other types
"isPartOf": validateOrganizations,
"url": validateUrls,

// TODO: add more?
};

const reviewFieldValidators = {
"reviewAspect": validateText,
"reviewBody": validateText,
}

function switchCodemetaContext(codemetaJSON, contextUrl) {
const previousCodemetaContext = codemetaJSON["@context"];
codemetaJSON["@context"] = contextUrl;
return previousCodemetaContext;
}
Comment on lines +161 to +165
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of altering the argument and returning the previous context; could you return a new object with the new context, and not change the argument? I think it would be less confusing, and removes the need to switch it back.


async function validateTerms(codemetaJSON) {
try {
await jsonld.expand(codemetaJSON, { safe: true });
} catch (validationError) {
if (validationError.details.event.code === "invalid property") {
setError(`Unknown field "${validationError.details.event.details.property}".`);
return false;
}
}
return true;
}

function validateCodemetaJSON(codemetaJSON) {
if (!Array.isArray(codemetaJSON) && typeof codemetaJSON != 'object') {
setError("Document must be an object (starting and ending with { and }), not ${typeof doc}.")
return false;
}
// TODO: validate id/@id

// TODO: check there is either type or @type but not both
var type = getDocumentType(doc);
var type = getDocumentType(codemetaJSON);
if (type === undefined) {
setError("Missing type (must be SoftwareSourceCode or SoftwareApplication).")
return false;
Expand All @@ -32,42 +195,29 @@ function validateDocument(doc) {
setError(`Wrong document type: must be "SoftwareSourceCode"/"SoftwareApplication", not ${JSON.stringify(type)}`)
return false;
}
else {
return Object.entries(doc).every((entry) => {
var fieldName = entry[0];
var subdoc = entry[1];
if (fieldName == "@context") {
// Was checked before
return true;
}
else if (fieldName == "type" || fieldName == "@type") {
// Was checked before
return true;
}
else if (isFieldFromOtherVersionToIgnore(fieldName)) {
// Do not check fields from other versions FIXME
return true;
}
else {
var validator = softwareFieldValidators[fieldName];
if (validator === undefined) {
// TODO: find if it's a field that belongs to another type,
// and suggest that to the user
setError(`Unknown field "${fieldName}".`)
return false;
}
else {
return validator(fieldName, subdoc);
}
return true;
}

function validateDocument(doc) {
return Object.entries(doc)
.filter(([fieldName]) => !isKeyword(fieldName))
.every(([fieldName, subdoc]) => {
const compactedFieldName = getCompactType(fieldName);
var validator = softwareFieldValidators[compactedFieldName];
if (validator === undefined) {
// TODO: find if it's a field that belongs to another type,
// and suggest that to the user
setError(`Unknown field "${compactedFieldName}".`)
return false;
} else {
return validator(compactedFieldName, subdoc);
}
});
}
}


async function parseAndValidateCodemeta(showPopup) {
var codemetaText = document.querySelector('#codemetaText').innerText;
let parsed, doc;
let parsed;

try {
parsed = JSON.parse(codemetaText);
Expand All @@ -79,18 +229,26 @@ async function parseAndValidateCodemeta(showPopup) {

setError("");

var isValid = validateDocument(parsed);
let isJSONValid = validateCodemetaJSON(parsed);

const previousCodemetaContext = switchCodemetaContext(parsed, INTERNAL_CONTEXT_URL);

let areTermsValid = await validateTerms(parsed);

const expanded = await jsonld.expand(parsed);
const doc = await jsonld.compact(expanded, INTERNAL_CONTEXT_URL);

switchCodemetaContext(parsed, previousCodemetaContext)

let isDocumentValid = validateDocument(doc);
if (showPopup) {
if (isValid) {
if (isJSONValid && areTermsValid && isDocumentValid) {
alert('Document is valid!')
}
else {
alert('Document is invalid.');
}
}

parsed["@context"] = LOCAL_CONTEXT_URL;
const expanded = await jsonld.expand(parsed);
doc = await jsonld.compact(expanded, LOCAL_CONTEXT_URL);
return doc;
}
4 changes: 4 additions & 0 deletions js/validation/primitives.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* Validators for native schema.org data types.
*/

function noValidation(fieldName, doc) {
return true;
}

// Validates an URL or an array of URLs
function validateUrls(fieldName, doc) {
return validateListOrSingle(fieldName, doc, (subdoc, inList) => {
Expand Down
Loading