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

feat: validate local and external references #26

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
c0ba854
feat: validate local and external references
probablyArth Mar 14, 2024
20eca6e
use getKeywordName for fetching keyword name for reference keyword
probablyArth Mar 17, 2024
5ce414d
use the existing JsoncInstance class
probablyArth Mar 17, 2024
a033849
add contextDialectUri to toplevel
probablyArth Mar 17, 2024
5cf6eed
Merge remote-tracking branch 'upstream/main' into feat-validate-refer…
probablyArth Mar 17, 2024
c913db3
lint
probablyArth Mar 19, 2024
3873847
Merge branch 'main' into feat-validate-references/#7
probablyArth Mar 19, 2024
d96ee47
temp commit
probablyArth Mar 27, 2024
6b09cc2
handle external reference JSON pointer
probablyArth Mar 28, 2024
899d3c3
Merge remote-tracking branch 'upstream/main' into feat-validate-refer…
probablyArth Mar 28, 2024
84c895c
merge
probablyArth Mar 28, 2024
a0abcd8
modify references logic according to the latest merge
probablyArth Mar 28, 2024
8700c8f
feat: anchor fragment
probablyArth Mar 28, 2024
aaafff9
fix relative ref
probablyArth Mar 28, 2024
def18f8
extract fetching file logic
probablyArth Mar 28, 2024
29ce34d
modify jsonc-instance
probablyArth Mar 28, 2024
69e3ba7
external references with absolute uri
probablyArth Mar 28, 2024
0159120
write cleaner statements
probablyArth Mar 28, 2024
21a7a53
fix absolute url regex
probablyArth Mar 29, 2024
cfb727e
add catch for linux on fs.watch
probablyArth Mar 29, 2024
4e02c20
remove catch for fs.watch
probablyArth Mar 29, 2024
1b44b78
resolve conflicts
probablyArth Mar 30, 2024
33afa77
set recursive flag to true for watch in workspace
probablyArth Apr 2, 2024
3dea88c
feat: identifiers, inactiveDocuments and referencesStore
probablyArth Apr 5, 2024
e2800ab
Merge remote-tracking branch 'upstream/main' into feat-validate-refer…
probablyArth Apr 5, 2024
1d97c25
pass value of ref instead of JsoncInstance
probablyArth Apr 5, 2024
d10b124
feat: validate references
probablyArth Apr 6, 2024
fc6f164
refactor: delete identifiers store, refactor references logic
probablyArth Apr 24, 2024
caaa0a1
remove redundant creation of JsoncInstance
probablyArth May 11, 2024
e85afb2
remove inactiveDocumentStore
probablyArth May 11, 2024
5b7a676
nothing should be exported from the server
probablyArth May 11, 2024
96a196d
move isSchema back to server.js
probablyArth May 11, 2024
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
45 changes: 45 additions & 0 deletions language-server/src/documents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { readFile } from "fs/promises";
import { fileURLToPath } from "url";
import { TextDocument } from "vscode-languageserver-textdocument";

/**
* documentStore for inactive documents
*
* `uri` => `TextDocument`
* @type {Map<string, TextDocument}
*/
const inactiveDocumentStore = new Map();

/**
* @param {import("vscode-languageserver").TextDocuments<TextDocument>} documents
* @param {string} uri
* @returns {Promise<TextDocument>}
*/
export const fetchDocument = async (documents, uri) => {
if (inactiveDocumentStore.has(uri)) {
return inactiveDocumentStore.get(uri);
}

let textDocument = documents.get(uri);

if (!textDocument) {
const instanceJson = await readFile(fileURLToPath(uri), "utf8");
textDocument = TextDocument.create(uri, "json", -1, instanceJson);
inactiveDocumentStore.set(uri, textDocument);
}
return textDocument;
};

/**
* @param {import("vscode-languageserver").TextDocuments<TextDocument>} documents
*/
export const doesDocumentExist = (documents, uri) => {
return documents.keys().includes(uri) || inactiveDocumentStore.has(uri);
};

/**
* @param {string} uri
*/
export const deleteFromInactiveDocumentStore = (uri) => {
return inactiveDocumentStore.delete(uri);
};
8 changes: 7 additions & 1 deletion language-server/src/json-schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,13 @@ const getEmbeddedDialectUri = (schemaInstance, contextDialectUri) => {
}
};

const keywordNameFor = (keywordUri, dialectUri) => {
/**
*
* @param {string} keywordUri
* @param {string} dialectUri
* @returns {string | undefined}
*/
export const keywordNameFor = (keywordUri, dialectUri) => {
try {
return getKeywordName(dialectUri, keywordUri);
} catch (error) {
Expand Down
11 changes: 11 additions & 0 deletions language-server/src/jsonc-instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ import { toAbsoluteUri, uriFragment } from "./util.js";


export class JsoncInstance {
/**
* @param {import("vscode-languageserver-textdocument").TextDocument} textDocument
* @param {import("jsonc-parser").Node | undefined} root
* @param {import("jsonc-parser").Node | undefined} node
* @param {string} pointer
* @param {*} annotations
*/
constructor(textDocument, root, node, pointer, annotations) {
this.textDocument = textDocument;
this.root = root;
Expand All @@ -14,6 +21,10 @@ export class JsoncInstance {
this.annotations = annotations;
}

/**
* @param {import("vscode-languageserver-textdocument").TextDocument} textDocument
* @returns {JsoncInstance}
*/
static fromTextDocument(textDocument) {
const json = textDocument.getText();
const root = parseTree(json, [], {
Expand Down
182 changes: 182 additions & 0 deletions language-server/src/references.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { doesDocumentExist, fetchDocument } from "./documents.js";
import { keywordNameFor } from "./json-schema.js";
import { JsoncInstance } from "./jsonc-instance.js";
import { getSemanticTokens } from "./semantic-tokens.js";
import { getSchemaResources, workspaceUri } from "./server.js";
probablyArth marked this conversation as resolved.
Show resolved Hide resolved
import { isAbsoluteUrl } from "./util.js";
import { workspaceSchemas } from "./workspace.js";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL, resolve } from "node:url";

/**
* @param {JsoncInstance} keywordInstance
* @param {string} dialectUri
*/
export const findRef = (keywordInstance, dialectUri) => {
const referenceKeywordIds = [
"https://json-schema.org/keyword/ref",
"https://json-schema.org/keyword/draft-04/ref"
];

const referenceKeywordNames = referenceKeywordIds.map((keywordId) => keywordNameFor(keywordId, dialectUri));
if (!referenceKeywordNames.includes(keywordInstance.value())) {
return;
}
const { pointer } = keywordInstance;

const valueInstance = keywordInstance.get("#" + pointer);

if (typeof valueInstance.value() !== "string") {
return;
}

return keywordInstance.pointer;
};

/**
* @param {import("vscode-languageserver").TextDocuments} documents
* @param {import("vscode-languageserver-textdocument").TextDocument} document
* @param {string} pointer
*/
export const validateReference = async (documents, document, pointer) => {
const documentJsonInstance = JsoncInstance.fromTextDocument(document);
const valueInstance = documentJsonInstance.get("#" + pointer);
const ref = valueInstance.value();
const { baseUrl, jsonPointer, anchorFragment } = extractUriInfo(ref);
/**
* @type {JsoncInstance | null}
*/
let documentInstance = documentJsonInstance;
if (!ref.startsWith("#")) {
documentInstance = await getReferencedInstance(documents, document, baseUrl);
}
if (documentInstance === null) {
return { valid: false, message: "Invalid external reference" };
}
if (jsonPointer !== null) {
if (documentInstance.get("#" + jsonPointer).value() === undefined) {
return { valid: false, message: `Invalid JSON pointer: ${jsonPointer}` };
}
}
if (anchorFragment !== null) {
if (!await searchAnchorFragment(documentInstance.textDocument, anchorFragment)) {
return { valid: false, message: `Invalid anchor fragment: ${anchorFragment}` };
}
}

return { valid: true };
};

/**
* @param {import("vscode-languageserver-textdocument").TextDocument} textDocument
* @returns {AsyncGenerator<{instance: import("./jsonc-instance.js").JsoncInstance, isEmbedded: boolean}>}
*/
const getIdentifiers = async function* (textDocument) {
for (const { dialectUri, schemaInstance } of await getSchemaResources(textDocument)) {
const idKeywordName = keywordNameFor("https://json-schema.org/keyword/id", dialectUri);
const idInstance = schemaInstance.step(idKeywordName);
if (idInstance.value() !== undefined) {
yield { instance: idInstance, isEmbedded: schemaInstance.startPosition().line !== 0 };
}
}
};

/**
* @param {import("vscode-languageserver").TextDocuments} documents
* @param {string} identifier
* @returns {Promise<JsoncInstance | null>}
*/
const findInstanceForAbsoluteIdentfier = async (documents, identifier) => {
for await (const documentUri of workspaceSchemas()) {
const textDocument = await fetchDocument(documents, documentUri);
for await (const { instance, isEmbedded } of getIdentifiers(textDocument)) {
if (!isEmbedded && instance.value() === identifier) {
return instance;
}
}
}
return null;
};

/**
* @param {import("vscode-languageserver").TextDocuments} documents
* @param {import("vscode-languageserver-textdocument").TextDocument} document
* @param {string} refWithoutFragment
* @returns {Promise<JsoncInstance | null>}
*/
const getReferencedInstance = async (documents, document, refWithoutFragment) => {
for await (const { instance } of getIdentifiers(document)) {
if (instance.value() === refWithoutFragment) {
return instance;
}
}
if (!workspaceUri) {
return null;
}
if (isAbsoluteUrl(refWithoutFragment)) {
return await findInstanceForAbsoluteIdentfier(documents, refWithoutFragment);
}


const schemaResources = await getSchemaResources(document);
const { dialectUri } = schemaResources[0];
const idKeywordName = keywordNameFor("https://json-schema.org/keyword/id", dialectUri);
const jsonInstance = JsoncInstance.fromTextDocument(document);

let fullReferenceUri;
const baseUri = jsonInstance.get(`#/${idKeywordName}`).value();
if (baseUri !== undefined) {
fullReferenceUri = resolve(baseUri, refWithoutFragment);
return await findInstanceForAbsoluteIdentfier(documents, fullReferenceUri);
} else {
fullReferenceUri = pathToFileURL(join(dirname(fileURLToPath(document.uri)), refWithoutFragment)).toString();
if (!doesDocumentExist(documents, fullReferenceUri)) {
return null;
}
return JsoncInstance.fromTextDocument(await fetchDocument(documents, fullReferenceUri));
}
};

/**
*
* @param {TextDocument} textDocument
* @param {string} anchorValue
*/
const searchAnchorFragment = async (textDocument, anchorValue) => {
const schemaResources = await getSchemaResources(textDocument);
for (const { dialectUri } of schemaResources) {
const anchorKeywordName = keywordNameFor(
"https://json-schema.org/keyword/anchor",
dialectUri
);
for (const { keywordInstance } of getSemanticTokens(schemaResources)) {
if (keywordInstance.value() === anchorKeywordName) {
const valueInstance = keywordInstance.get("#" + keywordInstance.pointer);
if (
typeof valueInstance.value() === "string" && valueInstance.value() === anchorValue
) {
return true;
}
}
}
}
return false;
};

/**
* @param {string} uri
* @returns {{baseUrl: string | null; jsonPointer: string | null; anchorFragment: string | null}}
*/
const extractUriInfo = (uri) => {
const result = { baseUrl: null, jsonPointer: null, anchorFragment: null };
const [baseUrl, fragment] = uri.split("#");
result.baseUrl = baseUrl;
if (fragment) {
if (fragment.startsWith("/")) {
result.jsonPointer = fragment;
} else {
result.anchorFragment = fragment;
}
}
return result;
};
Loading