diff --git a/.castor/website.php b/.castor/website.php index 7d92ed32d..3baac2a26 100644 --- a/.castor/website.php +++ b/.castor/website.php @@ -30,8 +30,9 @@ use Symfony\Component\Console\Input\InputOption; -// The demo website: a static page, in website/public, that audits a document -// with the validator, run by PHP built as WebAssembly. See website/README.md. +// The demo website: static pages, in website/public, that audit a document +// with the validator, and run the JSON-LD algorithms on one, with PHP built as +// WebAssembly. See website/README.md. #[AsTask(description: 'Installs the dependencies of the demo website')] function install(): void @@ -75,7 +76,7 @@ function build( ])); // What is embedded takes some of the memory of the WebAssembly module: - // only what bin/audit.php reads + // only what bin/audit.php and bin/playground.php read fs()->mirror($website, $app, finder() ->in(["{$website}/assets/images", "{$website}/bin", "{$website}/src", "{$website}/templates", "{$website}/vendor"]) // Composer copies the directories of the repository that Git ignores too @@ -94,7 +95,13 @@ function check(): void io()->title('Checking the website'); check_stack(wasmStack()); - test_page('website/tests/page.test.mjs', 'website/tests/format.test.mjs'); + test_page( + 'website/tests/page.test.mjs', + 'website/tests/format.test.mjs', + 'website/tests/loadUrl.test.mjs', + 'website/tests/permalink.test.mjs', + 'website/tests/playground.test.mjs', + ); } #[AsTask(description: 'Serves the demo website')] @@ -131,7 +138,8 @@ function wasmStack(): Stack ->php('8.5.12') // What the library, Twig and league/commonmark require ->extensions('ctype', 'dom', 'filter', 'libxml', 'mbstring') - // Filled by build(), assets/php.js runs /app/bin/audit.php + // Filled by build(), assets/php.js runs /app/bin/audit.php and + // /app/bin/playground.php ->embed('website/build/app', at: '/app') ->targets(Target::Web) ->outputDir('website/public/build') diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ff857bc6..27e5d42dc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -154,12 +154,13 @@ The latest figures, and what each of them measures, are in [BENCHMARKS.md](BENCH ### Demo website -These commands build the [demo website](website/README.md), that runs the validator in the browser: +These commands build the [demo website](website/README.md), that runs the validator and the JSON-LD +algorithms in the browser: Command | Description ---- | ----- -`castor website:build` | Builds the demo website: its assets, and PHP as WebAssembly with the validator -`castor website:check` | Checks, in node, that what is built boots, and audits a document +`castor website:build` | Builds the demo website: its assets, and PHP as WebAssembly with the library +`castor website:check` | Checks, in node, that what is built boots, audits a document, and runs the JSON-LD algorithms `castor website:serve` | Serves the demo website ### Vocabulary generation diff --git a/docs/json-ld.md b/docs/json-ld.md index 4fe44865f..9b91e2889 100644 --- a/docs/json-ld.md +++ b/docs/json-ld.md @@ -11,6 +11,9 @@ The library implements the W3C - [Deserialization to RDF](https://www.w3.org/TR/json-ld11-api/#deserialize-json-ld-to-rdf-algorithm) (`toRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter` - [Serialization from RDF](https://www.w3.org/TR/json-ld11-api/#serialize-rdf-as-json-ld-algorithm) (`fromRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter` +> [!TIP] +> Try them in your browser, in the [JSON-LD playground](https://structured-data-validator.jolicode.com/playground/). + ## Usage Create an instance of the algorithm and pass it the JSON-LD document you want to convert. diff --git a/website/README.md b/website/README.md index 96af4a32c..eaf4760c4 100644 --- a/website/README.md +++ b/website/README.md @@ -3,12 +3,17 @@ > [!TIP] > This demo website is deployed under https://structured-data-validator.jolicode.com/ -A static page that audits a document with the validator, in the browser: PHP is built as -WebAssembly, with [lyrixx/php-wasm-builder](https://github.com/lyrixx/php-wasm-builder), and the -library of this repository embedded in it. GitHub Pages serves `public/`, deployed from `main` by +Static pages, that run the library in the browser: PHP is built as WebAssembly, with +[lyrixx/php-wasm-builder](https://github.com/lyrixx/php-wasm-builder), and the library of this +repository embedded in it. GitHub Pages serves `public/`, deployed from `main` by `.github/workflows/website.yml`. -It comes from +- The **homepage**, at `/`, has the form of the validator, and its examples. +- The **validator**, at `/validator/`, audits a document, and shows the result. +- The **JSON-LD playground**, at `/playground/`, runs the JSON-LD algorithms on a document: expand, + compact, flatten, frame, to RDF and from RDF. + +The validator comes from [jolicode/structured-data-validator-demo](https://github.com/jolicode/structured-data-validator-demo), without its server: the editor and the tree of the properties are its ones, with another look. Fetching a URL needs a server, and is not here: a page can not read another website. Pretty-printing @@ -17,14 +22,63 @@ as its `bin/format-document.js` does in node. ## How it works -- `public/index.html` is the homepage. `assets/app.js` gives the document of its form, or one of - `assets/examples.js`, to PHP, and shows what it answers in place of the form. -- `bin/audit.php` is what PHP runs: it audits the document, and renders `templates/result.html.twig`, - the editor and the result, with Twig. -- `assets/php.js` loads PHP, and runs `bin/audit.php`. -- The footer of the homepage is the JoliCode open-source one, - [jolicode/oss-theme](https://github.com/jolicode/oss-theme): `castor website:build` downloads it - to `public/build/joli-footer.html`, and the homepage loads it. +`assets/php.js` loads PHP, and runs a script of `bin/`: the request is on its standard input, and its +answer on its standard output, as JSON. + +### The state of the pages + +The validator and the playground share a state: the document, and what the playground adds to it +(its tab, its context, its frame, its options). `assets/pageState.js` writes it: + +- in the fragment of the URL of the page, compressed by `assets/permalink.js`: a link to the page + opens it as it is, and its "Copy link" button copies this link; +- in the links of the menu: the validator opens the playground with its document, and the + playground the validator, that validates what was typed there. + +A state too long for a link is kept in the session storage of the tab, and the fragment is `#local`: +the pages still open each other, and reload, but "Copy link" is disabled. + +### The validator + +- `public/index.html` is the homepage. `assets/home.js` opens the page of the validator with the + document of its form, or one of `assets/examples.js`. Nothing is audited there: PHP is only + fetched ahead. +- `public/validator/index.html` is the page of the validator. It holds the frame of the result, the + editor and the toolbar, that shows as the page opens: PHP has to start before it answers, and the + document is there meanwhile. `assets/controllers/result_controller.js` runs the page: it gives + the document the page is opened with to PHP, and shows what it answers in this frame. Without a + document, it goes back to the homepage. The document is audited again as it is typed, once the + visitor pauses, as in the playground: PHP runs in the thread of the page, so a document that + takes long to audit waits for a longer pause. +- `bin/audit.php` is what PHP runs: it audits the document, and renders what is found with Twig, + the counts of the toolbar, `templates/counts.html.twig`, and the entities, + `templates/result.html.twig`. The settings of the audit are the ones of who opens the page: they + are not in the link. + +### The playground + +- `public/playground/index.html` is the page, and `assets/controllers/playground_controller.js` what + runs it: the algorithm of the selected tab runs again as the visitor types, on the document, with + the context or the frame it needs, and the options it reads. +- `bin/playground.php` is what PHP runs: an algorithm, on what it is given. It answers with the + output, or the error code of the specification. +- `assets/jsonLd.js` loads the remote contexts. PHP has no network in the browser: when a document + needs a context that is not there, `bin/playground.php` answers that it is missing, + `assets/loadUrl.js` fetches it, and PHP is asked again with it. The website of the context has to + allow it, with CORS headers. The schema.org context is the one the library ships, and is never + fetched. +- `assets/playgroundExamples.js` holds the examples. + +Canonicalization (RDFC-1.0) is not there: the library does not implement it. + +### Every page + +- `assets/editor.js` is the CodeMirror editor of the validator and of the playground. +- The header, with its menu, is written in each page: there is no layout to share it. The links are + relative: the website works under any path. +- The footer is the JoliCode open-source one, [jolicode/oss-theme](https://github.com/jolicode/oss-theme): + `castor website:build` downloads it to `public/build/joli-footer.html`, and the homepage and the + playground load it. ## Build it @@ -40,3 +94,5 @@ Command | Description `composer.json` declares the parent directory as a path repository: the website is built with the code of the working directory, not with a release. Run `castor website:build` again after a change: only the last step of the build of PHP runs again. + +A test file of `tests/` runs once it is listed in the `check()` task. diff --git a/website/assets/app.js b/website/assets/app.js deleted file mode 100644 index bac2fb365..000000000 --- a/website/assets/app.js +++ /dev/null @@ -1,60 +0,0 @@ -import { Application } from "@hotwired/stimulus"; -import HighlightController from "./controllers/highlight_controller.js"; -import ResultController from "./controllers/result_controller.js"; -import { examples } from "./examples.js"; -import { audit } from "./php.js"; -import { loadSettings } from "./validatorSettings.js"; - -const app = Application.start(); -app.register("highlight", HighlightController); -app.register("result", ResultController); - -const submitButtons = () => document.querySelectorAll('button[type="submit"]'); - -// Both the form of the homepage and the one of the result audit their "body" -// field, and show the result in place of the
they are in. Stimulus sees -// the new one, and starts its controllers. -document.addEventListener("submit", async (event) => { - event.preventDefault(); - - const form = event.target; - const errorElement = form.querySelector("[data-validation-error]"); - const { mergeSharedIdentifiers, allowPendingVocabulary } = loadSettings(); - - errorElement.textContent = ""; - submitButtons().forEach((button) => (button.disabled = true)); - - try { - const { html, error } = await audit({ - body: form.elements.body.value, - mergeSharedIdentifiers, - allowPendingVocabulary, - }); - - if (error) { - errorElement.textContent = error; - } else { - document.querySelector("main").outerHTML = html; - window.scrollTo(0, 0); - } - } catch (error) { - console.error(error); - errorElement.textContent = "The validator crashed on this document, see the console for details."; - } finally { - submitButtons().forEach((button) => (button.disabled = false)); - } -}); - -document.addEventListener("click", (event) => { - const example = event.target.closest("[data-example]"); - if (!example) { - return; - } - - const form = document.querySelector("form"); - form.elements.body.value = examples[example.dataset.example]; - form.requestSubmit(); -}); - -// Until then, submitting would reload the page -submitButtons().forEach((button) => (button.disabled = false)); diff --git a/website/assets/clipboard.js b/website/assets/clipboard.js new file mode 100644 index 000000000..2ae923abc --- /dev/null +++ b/website/assets/clipboard.js @@ -0,0 +1,28 @@ +// The "Copy" buttons of the pages: the button says whether it worked, for a +// moment. + +const FEEDBACK_DELAY = 1500; + +// The label of each button, and the timeout that brings it back: a second +// click comes while the button still says "Copied" +const labels = new WeakMap(); +const timeouts = new WeakMap(); + +export async function copyWithFeedback(text, button) { + if (!labels.has(button)) { + labels.set(button, button.textContent); + } + + try { + await navigator.clipboard.writeText(text); + button.textContent = "Copied"; + } catch { + button.textContent = "Not copied"; + } + + clearTimeout(timeouts.get(button)); + timeouts.set( + button, + setTimeout(() => (button.textContent = labels.get(button)), FEEDBACK_DELAY), + ); +} diff --git a/website/assets/controllers/playground_controller.js b/website/assets/controllers/playground_controller.js new file mode 100644 index 000000000..96714d8a0 --- /dev/null +++ b/website/assets/controllers/playground_controller.js @@ -0,0 +1,291 @@ +import { Controller } from "@hotwired/stimulus"; +import { copyWithFeedback } from "../clipboard.js"; +import { createEditor } from "../editor.js"; +import { OPTIONS, createJsonLdProcessor } from "../jsonLd.js"; +import { UNREADABLE, loadUrl } from "../loadUrl.js"; +import { readState, writeState } from "../pageState.js"; +import { normalizeState } from "../permalink.js"; +import { runPlayground } from "../php.js"; +import { DEFAULT_EXAMPLE, examples } from "../playgroundExamples.js"; + +// Typing runs the algorithm again, once the visitor pauses +const RUN_DELAY = 300; + +const OUTPUT_LABELS = { + expand: "Expanded document", + compact: "Compacted document", + flatten: "Flattened document", + frame: "Framed document", + toRdf: "RDF dataset, as N-Quads", + fromRdf: "JSON-LD document, from RDF", +}; + +// A context is served as JSON-LD by content negotiation +const load = async (url) => { + const answer = await loadUrl(url, { accept: "application/ld+json, application/json;q=0.9" }); + + return answer.error === UNREADABLE + ? { error: "Your browser could not read it: its website has to allow it with CORS headers, and to be reachable." } + : answer; +}; + +export default class extends Controller { + static targets = [ + "contextEditor", + "contextLabel", + "contextPanel", + "copyLink", + "copyOutput", + "documentEditor", + "documentLabel", + "error", + "frameEditor", + "framePanel", + "option", + "options", + "outputEditor", + "outputLabel", + "outputPanel", + "status", + "tab", + ]; + + async connect() { + this.process = createJsonLdProcessor({ run: runPlayground, load }); + this.state = normalizeState(examples[DEFAULT_EXAMPLE]); + + this.editors = { + // The document of every algorithm but one, that reads N-Quads + document: createEditor({ + parent: this.documentEditorTarget, + label: "Document", + onChange: (value) => this.edit(this.state.algorithm === "fromRdf" ? "nquads" : "document", value), + }), + context: createEditor({ + parent: this.contextEditorTarget, + label: "Context", + onChange: (value) => this.edit("context", value), + }), + frame: createEditor({ + parent: this.frameEditorTarget, + label: "Frame", + onChange: (value) => this.edit("frame", value), + }), + output: createEditor({ parent: this.outputEditorTarget, label: "Output", readOnly: true }), + }; + + // A permalink, or what the menu of the validator opens the playground with + const shared = await readState(); + + if (shared) { + const state = normalizeState(shared); + + // The N-Quads of the examples, when the link has none: its tab shows something + this.state = { ...state, nquads: state.nquads || examples.nquads.nquads }; + } else { + this.state.nquads = examples.nquads.nquads; + } + + this.render(); + this.run(); + } + + disconnect() { + clearTimeout(this.runTimeout); + } + + // The actions of the page + + selectTab({ currentTarget }) { + this.state.algorithm = currentTarget.dataset.algorithm; + this.render(); + this.changed({ now: true }); + } + + // The arrows move across the tabs, as in any tab list + moveTab(event) { + const tabs = this.tabTargets; + const index = tabs.indexOf(event.currentTarget); + const next = { ArrowLeft: index - 1, ArrowRight: index + 1, Home: 0, End: tabs.length - 1 }[event.key]; + + if (next === undefined) { + return; + } + + event.preventDefault(); + + const tab = tabs[(next + tabs.length) % tabs.length]; + tab.focus(); + tab.click(); + } + + loadExample({ currentTarget }) { + const { label, ...example } = examples[currentTarget.dataset.example]; + + // An example is a document with its context and its frame, or some N-Quads: + // what it does not hold stays + Object.assign(this.state, example); + this.render(); + this.changed({ now: true }); + } + + changeOption({ currentTarget }) { + const name = currentTarget.name; + + if (currentTarget.type === "checkbox") { + this.state.options[name] = currentTarget.checked; + } else if (name === "omitGraph") { + this.state.options[name] = { yes: true, no: false }[currentTarget.value] ?? null; + } else { + this.state.options[name] = currentTarget.value; + } + + this.changed({ now: currentTarget.type !== "text" }); + } + + copyLink() { + copyWithFeedback(location.href, this.copyLinkTarget); + } + + copyOutput() { + copyWithFeedback(this.editors.output.getValue(), this.copyOutputTarget); + } + + // What they do + + edit(field, value) { + this.state[field] = value; + this.changed(); + } + + changed({ now = false } = {}) { + clearTimeout(this.runTimeout); + this.runTimeout = setTimeout(() => this.run(), now ? 0 : RUN_DELAY); + } + + /** + * Runs the algorithm, one run at a time: PHP runs in the thread of the page. + * What changes meanwhile is run next, and only the last answer is shown. + */ + async run() { + this.writePermalink(); + + if (this.running) { + this.outdated = true; + + return; + } + + this.running = true; + this.statusTarget.textContent = this.ran ? "Running…" : "Loading PHP…"; + + try { + let answer; + + do { + this.outdated = false; + + const { algorithm, document, nquads, context, frame, options } = this.state; + + try { + answer = await this.process({ + algorithm, + document: algorithm === "fromRdf" ? nquads : document, + context, + frame, + options, + }); + } catch (error) { + console.error(error); + answer = { error: "The playground crashed on this document, see the console for details." }; + } + } while (this.outdated); + + this.ran = true; + this.show(answer); + } finally { + this.running = false; + this.statusTarget.textContent = ""; + } + } + + show({ output, language, error }) { + this.errorTarget.textContent = error ?? ""; + this.errorTarget.hidden = !error; + // The output of the last run that worked stays, dimmed: it does not blink + // while the document is being typed + this.outputEditorTarget.classList.toggle("opacity-40", Boolean(error)); + + if (error) { + return; + } + + this.editors.output.setLanguage(language === "json" ? "json" : "text"); + this.editors.output.setValue(output); + } + + /** + * Shows the state: the tab, its editors and its options. + */ + render() { + const { algorithm, options } = this.state; + const fromRdf = algorithm === "fromRdf"; + + for (const tab of this.tabTargets) { + const selected = tab.dataset.algorithm === algorithm; + + tab.setAttribute("aria-selected", String(selected)); + tab.tabIndex = selected ? 0 : -1; + + if (selected) { + this.outputPanelTarget.setAttribute("aria-labelledby", tab.id); + } + } + + this.documentLabelTarget.textContent = fromRdf ? "RDF dataset, as N-Quads" : "JSON-LD document"; + this.editors.document.setLanguage(fromRdf ? "text" : "json"); + this.editors.document.setValue(fromRdf ? this.state.nquads : this.state.document); + + this.contextPanelTarget.hidden = !["compact", "flatten"].includes(algorithm); + this.contextLabelTarget.textContent = algorithm === "flatten" ? "Context (optional)" : "Context"; + this.editors.context.setValue(this.state.context); + + this.framePanelTarget.hidden = algorithm !== "frame"; + this.editors.frame.setValue(this.state.frame); + + this.outputLabelTarget.textContent = OUTPUT_LABELS[algorithm]; + + for (const wrapper of this.optionTargets) { + const field = wrapper.querySelector("[name]"); + const value = options[field.name]; + + wrapper.hidden = !OPTIONS[field.name].algorithms.includes(algorithm); + + if (field.type === "checkbox") { + field.checked = value; + } else if (field.name === "omitGraph") { + field.value = value === null ? "" : value ? "yes" : "no"; + } else { + field.value = value; + } + } + + this.optionsTarget.hidden = this.optionTargets.every((wrapper) => wrapper.hidden); + } + + async writePermalink() { + // In the URL, and in the link of the menu to the validator, that validates + // the document: see pageState.js + const shareable = await writeState(this.state); + + // Another change came meanwhile, and writes its own + if (shareable === null) { + return; + } + + this.copyLinkTarget.disabled = !shareable; + this.copyLinkTarget.title = shareable + ? "Copy a link to this page, with its documents and its options" + : "These documents are too long to be shared in a link"; + } +} diff --git a/website/assets/controllers/result_controller.js b/website/assets/controllers/result_controller.js index 442c0c6aa..86e34c800 100644 --- a/website/assets/controllers/result_controller.js +++ b/website/assets/controllers/result_controller.js @@ -1,27 +1,34 @@ import { Controller } from "@hotwired/stimulus"; +import { copyWithFeedback } from "../clipboard.js"; +import { editorExtensions } from "../editor.js"; +import { readState, writeState } from "../pageState.js"; +import { audit } from "../php.js"; import { loadSettings, persistSettings } from "../validatorSettings.js"; -import * as autocomplete from "@codemirror/autocomplete"; -import * as commands from "@codemirror/commands"; import { htmlLanguage } from "@codemirror/lang-html"; import { json, jsonLanguage } from "@codemirror/lang-json"; -import * as language from "@codemirror/language"; import * as state from "@codemirror/state"; import * as view from "@codemirror/view"; import { configureNesting } from "@lezer/html"; -const defaultValue = `{ - "@context": "https://schema.org", - "@type": "Organization", - "url": "https://jolicode.com", - "name": [ - "Web development agency" - ], - "contactPoint": { - "@type": "ContactPoint", - "url": "https://jolicode.com/contact", - "contactType": "Customer service" - } -}`; +// The page of the validator, public/validator/index.html. Its frame is in the +// page, and shows as it opens: the editor, with the document the page is opened +// with, and the toolbar. PHP takes longer: it has to start, then to audit the +// document. What it answers, the counts and the entities of bin/audit.php, is +// shown in this frame, and again as the document is typed. + +// Typing validates the document again, once the visitor pauses. PHP runs in the +// thread of the page, that is frozen meanwhile: a document that takes long to +// audit waits for a longer pause, twice the time of its last audit. +const RUN_DELAY = 300; +const MAX_RUN_DELAY = 2000; + +// Lets the page paint what says that PHP runs, before PHP freezes it. A hidden +// tab has no frame to wait for. +const painted = () => + new Promise((resolve) => { + requestAnimationFrame(() => setTimeout(resolve)); + setTimeout(resolve, 100); + }); // override the html language configuration to support the nested json-ld blocks const html = htmlLanguage.configure({ @@ -36,12 +43,19 @@ const html = htmlLanguage.configure({ ]), }); +// A page, or a JSON document: told from where the document starts +const START_LENGTH = 100; +const isPage = (start) => /^\s* (page ? html : json()); + +const violationMarker = new (class extends view.GutterMarker { + elementClass = "cm-violationLineGutter"; +})(); + // data-start / data-end carry "line:column" pairs computed by PHP, valid only // against the exact document it audited. Should the two ever drift // apart, that must degrade to "no marker" rather than throw: doc.line() raises -// a RangeError, and one raised inside the transactionExtender below would -// abort the whole controller boot, leaving the visitor with a bare textarea -// and no editor at all. +// a RangeError. const lineStart = (doc, rawLine) => { const line = parseInt(rawLine, 10); @@ -56,10 +70,15 @@ const lineStart = (doc, rawLine) => { export default class extends Controller { static targets = [ - "codemirror", + "copyLink", + "counts", + "editor", + "entity", + "error", "expandButton", "formatButton", "nodes", + "pending", "settingsWrapper", "settingsButton", "settingsPanel", @@ -67,25 +86,14 @@ export default class extends Controller { "settingAllowPending", "settingAutoExpandWarnings", "showDescriptions", + "status", "warnings", ]; - initialize() { - this.setupCodemirror(); - } - connect() { - // the errors are always shown, the warnings of an entity are folded - // unless the settings say otherwise - const { autoExpandWarnings, showDescriptions, expandTree } = loadSettings(); - - this.warningsTargets.forEach((warnings) => { - warnings.open = autoExpandWarnings; - }); + const { showDescriptions } = loadSettings(); - if (this.hasShowDescriptionsTarget) { - this.showDescriptionsTarget.checked = showDescriptions; - } + this.showDescriptionsTarget.checked = showDescriptions; this.nodesTarget.toggleAttribute("data-hide-descriptions", !showDescriptions); // "toggle" does not bubble: caught on its way down, and coalesced, as @@ -96,19 +104,190 @@ export default class extends Controller { }; this.nodesTarget.addEventListener("toggle", this.onBranchToggle, true); - // the tree is rendered collapsed: expanded again, if "Expand all" was the - // last choice - if (expandTree) { - this.treeBranches().forEach((branch) => { - branch.open = true; - }); - } - this.refreshExpandButton(); + this.open(); } disconnect() { this.nodesTarget.removeEventListener("toggle", this.onBranchToggle, true); cancelAnimationFrame(this.refreshFrame); + clearTimeout(this.runTimeout); + this.editorView?.destroy(); + } + + /** + * The document the page is opened with: the one of the homepage, of a link, + * or of the playground, see pageState.js. The editor shows it at once, then + * it is validated. + */ + async open() { + // what the playground added to the state stays: it opens as it was left + this.shared = (await readState()) ?? {}; + + const body = typeof this.shared.document === "string" ? this.shared.document : ""; + + if (body.trim() === "") { + // nothing to validate: the homepage has the form + location.replace("../"); + + return; + } + + this.setupEditor(body); + // the menu opens the playground with the document, validated or not + this.share(body); + this.run(); + } + + // What is typed is validated once the visitor pauses, the rest at once + changed({ now = false } = {}) { + clearTimeout(this.runTimeout); + this.runTimeout = setTimeout(() => this.run(), now ? 0 : this.runDelay ?? RUN_DELAY); + } + + /** + * Audits what the editor holds, one audit at a time: what changes meanwhile + * is audited next, and only the last answer is shown. + */ + async run() { + // the settings are saved before the page has read its document + if (!this.editorView) { + return; + } + + if (this.running) { + this.outdated = true; + + return; + } + + this.running = true; + // the first validation of the page is said where its result comes + this.statusTarget.textContent = this.hasPendingTarget ? "" : "Validating…"; + + try { + let answer; + let body; + + do { + this.outdated = false; + await painted(); + + body = this.editorView.state.doc.toString(); + + const { mergeSharedIdentifiers, allowPendingVocabulary } = loadSettings(); + const start = performance.now(); + + try { + answer = await audit({ body, mergeSharedIdentifiers, allowPendingVocabulary }); + } catch (error) { + console.error(error); + answer = { error: "The validator crashed on this document, see the console for details." }; + } + + this.runDelay = Math.min(MAX_RUN_DELAY, Math.max(RUN_DELAY, 2 * (performance.now() - start))); + } while (this.outdated); + + this.show(answer, body); + } finally { + this.running = false; + this.statusTarget.textContent = ""; + } + } + + // "counts" and "html" are rendered by PHP, see bin/audit.php + show({ counts, html, error }, body) { + this.errorTarget.textContent = error ?? ""; + // the result of the last document that was validated stays, dimmed: it + // does not blink while the document is being typed + this.countsTarget.classList.toggle("opacity-40", Boolean(error)); + this.nodesTarget.classList.toggle("opacity-40", Boolean(error)); + + if (error) { + // the first validation of the page: nothing is being validated any more + if (this.hasPendingTarget) { + this.pendingTarget.remove(); + } + + return; + } + + this.countsTarget.innerHTML = counts; + + // what the visitor unfolded stays so, as long as the result keeps its shape + const unfolded = this.foldable().map((branch) => branch.open); + + // the same result is not rendered again: nothing blinks while typing what + // does not change it + if (html !== this.shown) { + this.nodesTarget.innerHTML = html; + this.shown = html; + } + + const foldable = this.foldable(); + + if (!this.settingsSaved && unfolded.length > 0 && unfolded.length === foldable.length) { + foldable.forEach((branch, index) => { + branch.open = unfolded[index]; + }); + } else { + this.fold(); + } + this.settingsSaved = false; + + // nothing to describe, and nothing to expand, when no structured data is found + this.showDescriptionsTarget.disabled = !this.hasEntityTarget; + this.expandButtonTarget.disabled = !this.hasEntityTarget; + this.refreshExpandButton(); + + this.markViolations(); + this.share(body); + } + + /** + * Writes the document the page is opened with, then each one it audits, in + * the URL, and in the link of the menu to the playground, that opens with it: + * see pageState.js. A link to the page audits the document again, with the + * settings of who opens it. + */ + async share(document) { + const shareable = await writeState({ ...this.shared, document }); + + // another document took the place of this one meanwhile, and writes its own + if (shareable === null) { + return; + } + + this.copyLinkTarget.disabled = !shareable; + this.copyLinkTarget.title = shareable + ? "Copy a link to this result: opening it validates this document again" + : "This document is too long to be shared in a link"; + } + + copyLink() { + copyWithFeedback(location.href, this.copyLinkTarget); + } + + // what folds in the result: the warnings of each entity, and the branches of + // its property tree + foldable() { + return [...this.nodesTarget.querySelectorAll("details")]; + } + + // a result as it first shows, by the settings + fold() { + // the errors are always shown, the warnings of an entity are folded + // unless the settings say otherwise + const { autoExpandWarnings, expandTree } = loadSettings(); + + this.warningsTargets.forEach((warnings) => { + warnings.open = autoExpandWarnings; + }); + + // the tree is rendered collapsed: expanded again, if "Expand all" was the + // last choice + this.treeBranches().forEach((branch) => { + branch.open = expandTree; + }); } // the branches of the property tree: the warnings list of an entity is not one @@ -130,10 +309,6 @@ export default class extends Controller { } refreshExpandButton() { - if (!this.hasExpandButtonTarget) { - return; - } - const anyOpen = this.treeBranches().some((branch) => branch.open); this.expandButtonTarget.textContent = anyOpen ? "Collapse all" : "Expand all"; @@ -149,28 +324,32 @@ export default class extends Controller { } toggleSettings() { - const shouldOpen = this.settingsPanelTarget.classList.contains("hidden"); + if (!this.settingsPanelTarget.classList.contains("hidden")) { + this.closeSettings(); - if (shouldOpen) { - const settings = loadSettings(); - this.settingMergeNodesTarget.checked = settings.mergeSharedIdentifiers; - this.settingAllowPendingTarget.checked = settings.allowPendingVocabulary; - this.settingAutoExpandWarningsTarget.checked = settings.autoExpandWarnings; + return; } - this.settingsPanelTarget.classList.toggle("hidden", !shouldOpen); - this.settingsButtonTarget.setAttribute("aria-expanded", shouldOpen ? "true" : "false"); - } + const settings = loadSettings(); + this.settingMergeNodesTarget.checked = settings.mergeSharedIdentifiers; + this.settingAllowPendingTarget.checked = settings.allowPendingVocabulary; + this.settingAutoExpandWarningsTarget.checked = settings.autoExpandWarnings; - closeSettingsOnOutsideClick(event) { - if (this.settingsPanelTarget.classList.contains("hidden") || this.settingsWrapperTarget.contains(event.target)) { - return; - } + this.settingsPanelTarget.classList.remove("hidden"); + this.settingsButtonTarget.setAttribute("aria-expanded", "true"); + } + closeSettings() { this.settingsPanelTarget.classList.add("hidden"); this.settingsButtonTarget.setAttribute("aria-expanded", "false"); } + closeSettingsOnOutsideClick(event) { + if (!this.settingsWrapperTarget.contains(event.target)) { + this.closeSettings(); + } + } + // audit again so that the settings applied by PHP - merging and pending // vocabulary - take effect saveSettings() { @@ -180,16 +359,19 @@ export default class extends Controller { autoExpandWarnings: this.settingAutoExpandWarningsTarget.checked, }); - this.codemirrorTarget.form.requestSubmit(); + this.closeSettings(); + // the result shows again as these settings say + this.settingsSaved = true; + this.changed({ now: true }); } // the audit reports lines and columns: once the document is reformatted, // it is audited again async format() { - const form = this.codemirrorTarget.form; - const errorElement = form.querySelector("[data-validation-error]"); + if (!this.editorView) { + return; + } - errorElement.textContent = ""; this.formatButtonTarget.disabled = true; try { @@ -198,7 +380,7 @@ export default class extends Controller { const { content, error } = await formatDocument(this.editorView.state.doc.toString()); if (error) { - errorElement.textContent = error; + this.errorTarget.textContent = error; return; } @@ -206,207 +388,115 @@ export default class extends Controller { this.editorView.dispatch({ changes: { from: 0, to: this.editorView.state.doc.length, insert: content }, }); - form.requestSubmit(); + this.changed({ now: true }); } finally { this.formatButtonTarget.disabled = false; } } - setupCodemirror() { - let compartmentInitialized = false; - const compartmentEffects = []; - - // compute if a language change is required - const computeCurrentLanguage = (tr) => { - if (compartmentInitialized && !tr.docChanged) { - return null; - } + // the editor of every page, with the language and the gutters of this one + setupEditor(doc) { + const languageCompartment = new state.Compartment(); - const docIsHTML = /^\s* { + const page = isPage(tr.newDoc.sliceString(0, START_LENGTH)); - if (compartmentInitialized && docIsHTML === stateIsHTML) { + if (!tr.docChanged || page === isPage(tr.startState.doc.sliceString(0, START_LENGTH))) { return null; } - return docIsHTML ? html : json(); - }; - - // listen to the editor state to set the language and the gutters - // codemirror would not let us use two compartments - const compartment = new state.Compartment(); - const compartmentExtension = state.EditorState.transactionExtender.of( - (tr) => { - const currentLanguage = computeCurrentLanguage(tr); - - if (compartmentInitialized) { - return currentLanguage === null - ? null - : { - effects: compartment.reconfigure([ - currentLanguage, - ...compartmentEffects, - ]), - }; - } - - compartmentInitialized = true; - - const violationGutterMarker = new (class extends view.GutterMarker { - constructor() { - super(); - this.elementClass = "cm-violationLineGutter"; - } - })(); - - const ranges = []; - const positions = []; - - this.nodesTarget.querySelectorAll("[data-start]").forEach((node) => { - if (typeof node.dataset.invalid === "undefined") { - return; - } - - // a single range splits to a one-element list, so the pipe-joined and - // the lone case are the same code - node.dataset.start.split("|").forEach((start) => { - const from = lineStart(tr.startState.doc, start.split(":")[0]); - - if (from !== null) { - positions.push(from); - } - }); - }); + return { effects: languageCompartment.reconfigure(languageOf(page)) }; + }); - positions.forEach((value, index) => { - if (positions.indexOf(value) === index) { - ranges.push(violationGutterMarker.range(value)); + // filled by markViolations(), for each result + this.violations = new state.Compartment(); + + this.editorView = new view.EditorView({ + doc, + parent: this.editorTarget, + extensions: editorExtensions([ + view.lineNumbers(), + this.violations.of([]), + languageCompartment.of(languageOf(isPage(doc.slice(0, START_LENGTH)))), + followDocument, + view.EditorView.contentAttributes.of({ "aria-label": "Document" }), + view.EditorView.updateListener.of((update) => { + if (update.docChanged) { + this.changed(); } - }); + }), + ]), + }); + } - if (ranges.length) { - compartmentEffects.push( - view.lineNumberMarkers.of(state.RangeSet.of(ranges, true)) - ); - } + // marks, in the gutter, the lines of the document that the result reports + markViolations() { + const doc = this.editorView.state.doc; + const positions = new Set(); - compartmentEffects.push(view.lineNumbers()); + this.nodesTarget.querySelectorAll("[data-start][data-invalid]").forEach((node) => { + // a single range splits to a one-element list, so the pipe-joined and + // the lone case are the same code + node.dataset.start.split("|").forEach((start) => { + const from = lineStart(doc, start.split(":")[0]); - if (currentLanguage === null) { - return { - effects: compartment.reconfigure(compartmentEffects), - }; + if (from !== null) { + positions.add(from); } - - return { - effects: compartment.reconfigure([ - currentLanguage, - ...compartmentEffects, - ]), - }; - } - ); - - const customSelectionStyle = view.EditorView.baseTheme({ - ".cm-selectionBackground": { - backgroundColor: "rgb(255 255 100)", - }, + }); }); - const extensions = (() => [ - view.highlightActiveLineGutter(), - view.highlightSpecialChars(), - commands.history(), - view.drawSelection(), - view.dropCursor(), - state.EditorState.allowMultipleSelections.of(true), - language.indentOnInput(), - language.syntaxHighlighting(language.defaultHighlightStyle, { - fallback: true, - }), - language.bracketMatching(), - compartment.of([]), - compartmentExtension, - autocomplete.closeBrackets(), - autocomplete.autocompletion(), - view.rectangularSelection(), - view.crosshairCursor(), - view.highlightActiveLine(), - view.keymap.of([ - ...autocomplete.closeBracketsKeymap, - ...commands.defaultKeymap, - ...commands.historyKeymap, - commands.indentWithTab, - ...autocomplete.completionKeymap, - ]), - customSelectionStyle, - ])(); + const ranges = [...positions].map((from) => violationMarker.range(from)); - // create the editor - const editorView = new view.EditorView({ - doc: this.codemirrorTarget.value || defaultValue, - extensions, + this.editorView.dispatch({ + effects: this.violations.reconfigure(view.lineNumberMarkers.of(state.RangeSet.of(ranges, true))), }); - this.editorView = editorView; - this.codemirrorTarget.parentNode.insertBefore(editorView.dom, this.codemirrorTarget); - this.codemirrorTarget.style.display = "none"; + } - // app.js audits what the textarea holds, once the event reaches the document - this.codemirrorTarget.form.addEventListener("submit", () => { - this.codemirrorTarget.value = editorView.state.doc.toString(); - }); - - // force an initial configuration of our comprtment - editorView.dispatch({ - effects: compartment.reconfigure(html), - }); + // a click on what the result locates selects it in the document + showInDocument(event) { + // a link of an issue is followed, not taken for its issue + const node = event.target.closest("a, [data-start]"); + if (!node || !node.dataset.start || !node.dataset.end) { + return; + } - // handle the clicks on the nodes - this.nodesTarget.addEventListener("click", (e) => { - // a link of an issue is followed, not taken for its issue - const node = e.target.closest("a, [data-start]"); + event.preventDefault(); + // several ranges are joined with a pipe: the first one is selected + const start = node.dataset.start.split("|")[0].split(":"); + const end = node.dataset.end.split("|")[0].split(":"); - if (node && node.dataset.start && node.dataset.end) { - e.preventDefault(); - // several ranges are joined with a pipe: the first one is selected - const start = node.dataset.start.split("|")[0].split(":"); - const end = node.dataset.end.split("|")[0].split(":"); + // tested before computing anything, so an approximate range cannot + // throw on its way to being ignored + if (start.length > 2 && start[2] === "approx") { + return; + } - // tested before computing anything, so an approximate range cannot - // throw on its way to being ignored - if (start.length > 2 && start[2] === "approx") { - return; - } + const doc = this.editorView.state.doc; + const startFrom = lineStart(doc, start[0]); + const endFrom = lineStart(doc, end[0]); - const startFrom = lineStart(editorView.state.doc, start[0]); - const endFrom = lineStart(editorView.state.doc, end[0]); + if (startFrom === null || endFrom === null) { + return; + } - if (startFrom === null || endFrom === null) { - return; - } + // a column can overrun its line even when the line number is sound, + // and EditorSelection rejects an out-of-document position + const bookmarkStart = Math.max(0, Math.min(startFrom + parseInt(start[1], 10) - 1, doc.length)); + const bookmarkEnd = Math.max(0, Math.min(endFrom + parseInt(end[1], 10) - 1, doc.length)); - // a column can overrun its line even when the line number is sound, - // and EditorSelection rejects an out-of-document position - const docLength = editorView.state.doc.length; - const bookmarkStart = Math.max(0, Math.min(startFrom + parseInt(start[1], 10) - 1, docLength)); - const bookmarkEnd = Math.max(0, Math.min(endFrom + parseInt(end[1], 10) - 1, docLength)); - - editorView.dispatch({ - selection: { - anchor: bookmarkEnd, - head: bookmarkStart, - }, - }); - editorView.dispatch( - editorView.state.update({ - effects: view.EditorView.scrollIntoView(bookmarkEnd, { - y: 'center', - x: 'center', - }), - }) - ); - } + this.editorView.dispatch({ + selection: { + anchor: bookmarkEnd, + head: bookmarkStart, + }, + effects: view.EditorView.scrollIntoView(bookmarkEnd, { + y: "center", + x: "center", + }), }); } } diff --git a/website/assets/editor.js b/website/assets/editor.js new file mode 100644 index 000000000..8c4b10713 --- /dev/null +++ b/website/assets/editor.js @@ -0,0 +1,98 @@ +// The CodeMirror editor of the pages: the result of the validator adds its +// gutter markers to these extensions, the playground makes its editors with +// createEditor(). + +import * as autocomplete from "@codemirror/autocomplete"; +import * as commands from "@codemirror/commands"; +import { json } from "@codemirror/lang-json"; +import * as language from "@codemirror/language"; +import * as state from "@codemirror/state"; +import * as view from "@codemirror/view"; + +const selectionStyle = view.EditorView.baseTheme({ + ".cm-selectionBackground": { + backgroundColor: "rgb(255 255 100)", + }, +}); + +/** + * What every editor is made of. "own" is what an editor adds: its language, + * its gutters. + */ +export function editorExtensions(own = []) { + return [ + view.highlightActiveLineGutter(), + view.highlightSpecialChars(), + commands.history(), + view.drawSelection(), + view.dropCursor(), + state.EditorState.allowMultipleSelections.of(true), + language.indentOnInput(), + language.syntaxHighlighting(language.defaultHighlightStyle, { + fallback: true, + }), + language.bracketMatching(), + ...own, + autocomplete.closeBrackets(), + autocomplete.autocompletion(), + view.rectangularSelection(), + view.crosshairCursor(), + view.highlightActiveLine(), + view.keymap.of([ + ...autocomplete.closeBracketsKeymap, + ...commands.defaultKeymap, + ...commands.historyKeymap, + commands.indentWithTab, + ...autocomplete.completionKeymap, + ]), + selectionStyle, + ]; +} + +// "json", or "text" for what has no grammar here, as N-Quads +const languageExtension = (name) => (name === "json" ? json() : []); + +// Marks what setValue() writes, that is not typed: onChange is not told +const written = state.Annotation.define(); + +/** + * Makes an editor in "parent". "onChange" is given what is typed, "label" names + * the editor for a screen reader. A read-only editor still takes the focus, to + * select and copy what it shows. + */ +export function createEditor({ parent, label, doc = "", language: name = "json", readOnly = false, onChange = null }) { + const languageCompartment = new state.Compartment(); + + const editorView = new view.EditorView({ + doc, + parent, + extensions: editorExtensions([ + view.lineNumbers(), + languageCompartment.of(languageExtension(name)), + state.EditorState.readOnly.of(readOnly), + view.EditorView.contentAttributes.of({ "aria-label": label }), + view.EditorView.updateListener.of((update) => { + if (onChange && update.docChanged && !update.transactions.some((transaction) => transaction.annotation(written))) { + onChange(update.state.doc.toString()); + } + }), + ]), + }); + + return { + getValue: () => editorView.state.doc.toString(), + setLanguage(name) { + editorView.dispatch({ effects: languageCompartment.reconfigure(languageExtension(name)) }); + }, + setValue(value) { + if (value === editorView.state.doc.toString()) { + return; + } + + editorView.dispatch({ + annotations: written.of(true), + changes: { from: 0, to: editorView.state.doc.length, insert: value }, + }); + }, + }; +} diff --git a/website/assets/home.js b/website/assets/home.js new file mode 100644 index 000000000..5ff8d7fe1 --- /dev/null +++ b/website/assets/home.js @@ -0,0 +1,48 @@ +// The homepage, public/index.html: its form, or one of its examples, opens the +// page of the validator with a document. Nothing is audited here. + +import { examples } from "./examples.js"; +import { stateUrl } from "./pageState.js"; + +const form = document.querySelector("form"); +const errorElement = form.querySelector("[data-validation-error]"); + +// The validator reads the document in the fragment of its URL, or in the +// session storage when it is too long for a URL: see pageState.js +async function validate(body) { + if (body.trim() === "") { + errorElement.textContent = "Please enter some code to validate."; + + return; + } + + const url = await stateUrl("validator/", { document: body }); + + if (!url.includes("#")) { + errorElement.textContent = "This document is too long for a link, and your browser gives this page no storage to hand it to the validator."; + + return; + } + + errorElement.textContent = ""; + location.assign(url); +} + +form.addEventListener("submit", (event) => { + event.preventDefault(); + validate(form.elements.body.value); +}); + +document.addEventListener("click", (event) => { + const example = event.target.closest("[data-example]"); + if (!example) { + return; + } + + // Shown in the form too: it is there when the visitor comes back + form.elements.body.value = examples[example.dataset.example]; + validate(form.elements.body.value); +}); + +// Until then, submitting would reload the page +form.querySelector('button[type="submit"]').disabled = false; diff --git a/website/assets/jsonLd.js b/website/assets/jsonLd.js new file mode 100644 index 000000000..5fabb1d97 --- /dev/null +++ b/website/assets/jsonLd.js @@ -0,0 +1,99 @@ +// Runs a JSON-LD algorithm, with the remote contexts of the document, without +// the DOM: playground.js wires it to the page, tests/playground.test.mjs tests +// it in node. +// +// PHP WebAssembly has no network. bin/playground.php answers with the documents +// it misses, a remote context most of the time: they are fetched here, by the +// browser, and PHP is asked again with them, until it misses nothing. A context +// that loads another one is found this way too. + +// What a single document may load: each one is a run of PHP more +export const MAX_DOCUMENTS = 20; + +export const ALGORITHMS = ["expand", "compact", "flatten", "frame", "toRdf", "fromRdf"]; + +// The options of bin/playground.php, and the algorithms that read them +export const OPTIONS = { + base: { default: "", algorithms: ["expand", "compact", "flatten", "frame", "toRdf"] }, + ordered: { default: false, algorithms: ["expand", "compact", "frame", "toRdf", "fromRdf"] }, + compactArrays: { default: true, algorithms: ["compact", "flatten", "frame"] }, + compactToRelative: { default: true, algorithms: ["compact", "flatten"] }, + // null lets the algorithm decide: omitted, in JSON-LD 1.1 + omitGraph: { default: null, values: [null, true, false], algorithms: ["frame"] }, + produceGeneralizedRdf: { default: false, algorithms: ["toRdf"] }, + rdfDirection: { default: "", values: ["", "i18n-datatype", "compound-literal"], algorithms: ["toRdf", "fromRdf"] }, + useNativeTypes: { default: false, algorithms: ["fromRdf"] }, + useRdfType: { default: false, algorithms: ["fromRdf"] }, +}; + +export const defaultOptions = () => + Object.fromEntries(Object.entries(OPTIONS).map(([name, option]) => [name, option.default])); + +/** + * The options as bin/playground.php expects them, whatever is given: the ones + * of a permalink are written by anyone. + */ +export function normalizeOptions(given) { + const options = defaultOptions(); + + for (const [name, { default: byDefault, values }] of Object.entries(OPTIONS)) { + const value = given?.[name]; + + if (values ? values.includes(value) : typeof value === typeof byDefault) { + options[name] = value; + } + } + + return options; +} + +/** + * Gives the function that runs an algorithm. "run" is the runPlayground() of + * php.js, "load" resolves with the { body } of a URL, or the { error } that + * says why it is not loaded, as loadUrl() does. + * + * The function resolves with the { output } of the algorithm and its + * { language }, or the { error } that says why there is none. + */ +export function createJsonLdProcessor({ run, load }) { + // What was fetched, for as long as the page lives: typing in the document + // runs the algorithm again, not the requests + const fetched = new Map(); + // What the last run read, given again without waiting for PHP to miss it + let needed = []; + + return async function process({ algorithm, document, context = "", frame = "", options = {} }) { + const documents = Object.fromEntries(needed.map((url) => [url, fetched.get(url)])); + + // Each run gives PHP one document more, at least: it ends + for (;;) { + const answer = await run({ algorithm, document, context, frame, options: normalizeOptions(options), documents }); + + if (!answer.missing?.length) { + if (answer.loaded) { + needed = answer.loaded; + } + + return answer; + } + + for (const url of answer.missing) { + if (Object.keys(documents).length >= MAX_DOCUMENTS) { + return { error: `This document loads more than ${MAX_DOCUMENTS} remote documents.` }; + } + + if (!fetched.has(url)) { + const { body, error } = await load(url); + + if (error) { + return { error: `${url} could not be loaded. ${error}` }; + } + + fetched.set(url, body); + } + + documents[url] = fetched.get(url); + } + } + }; +} diff --git a/website/assets/loadUrl.js b/website/assets/loadUrl.js new file mode 100644 index 000000000..e91e9ad8d --- /dev/null +++ b/website/assets/loadUrl.js @@ -0,0 +1,101 @@ +// Loads the document of a URL, without the DOM: home.js wires it to the page, +// the playground loads the remote contexts of a document with it, see +// jsonLd.js, and tests/loadUrl.test.mjs tests it in node. +// +// A browser only lets a page read another website when that website allows it, +// with CORS headers, and most do not. Loading any page needs a server, a CORS +// proxy: it would be a second try here, when the website refuses. + +// The one of bin/audit.php, that refuses a larger document +const MAX_DOCUMENT_SIZE = 2 * 1024 * 1024; + +const TIMEOUT = 15_000; + +const INVALID_URL = "Please enter the URL of a page, starting with http:// or https://."; +const TOO_LARGE = "This document is too large to be validated."; +// fetch does not say whether the website refused, or the network failed. +// Exported for the playground, that says it of a context, not of a page. +export const UNREADABLE = + "This page could not be read from your browser: most websites do not let another website read their pages. Paste its source code instead."; + +// A page, or a JSON-LD document +const ACCEPT = "text/html,application/ld+json,application/json;q=0.9,*/*;q=0.8"; + +/** + * Resolves with the { body } of the document, or the { error } that says why + * it is not loaded. "accept" is what is asked for: the playground asks for + * JSON-LD, as a context is often served by content negotiation. + */ +export async function loadUrl(url, { accept = ACCEPT } = {}) { + const target = httpUrl(url); + if (target === null) { + return { error: INVALID_URL }; + } + + const response = await fetch(target, { + // A website that allows every origin is refused when cookies are sent + credentials: "omit", + // A safelisted header: the browser does not ask the website first + headers: { Accept: accept }, + signal: AbortSignal.timeout(TIMEOUT), + }).catch(() => null); + + if (response === null) { + return { error: UNREADABLE }; + } + + const contentType = response.headers.get("Content-Type") ?? ""; + + if (!response.ok) { + return refuse(response, `This page answered with the HTTP status ${response.status}.`); + } + if (contentType && !/html|json|^text\//i.test(contentType)) { + return refuse(response, "This URL is neither a HTML page nor a JSON document."); + } + if (Number(response.headers.get("Content-Length")) > MAX_DOCUMENT_SIZE) { + return refuse(response, TOO_LARGE); + } + + const buffer = await response.arrayBuffer().catch(() => null); + + if (buffer === null) { + return { error: UNREADABLE }; + } + if (buffer.byteLength > MAX_DOCUMENT_SIZE) { + return { error: TOO_LARGE }; + } + + return { body: decode(new Uint8Array(buffer), contentType) }; +} + +function httpUrl(url) { + try { + const { protocol, href } = new URL(url.trim()); + + return protocol === "http:" || protocol === "https:" ? href : null; + } catch { + return null; + } +} + +function refuse(response, error) { + // Not downloaded any further + response.body?.cancel().catch(() => {}); + + return { error }; +} + +// response.text() reads everything as UTF-8: the charset is the one of the +// Content-Type header, or the one a HTML page declares in its first bytes +function decode(bytes, contentType) { + const charset = + /charset\s*=\s*"?([^\s;"]+)/i.exec(contentType)?.[1] ?? + /]+charset\s*=\s*["']?([\w-]+)/i.exec(new TextDecoder("latin1").decode(bytes.subarray(0, 1024)))?.[1]; + + try { + return new TextDecoder(charset).decode(bytes); + } catch { + // A charset that the browser does not know + return new TextDecoder().decode(bytes); + } +} diff --git a/website/assets/pageState.js b/website/assets/pageState.js new file mode 100644 index 000000000..afb910746 --- /dev/null +++ b/website/assets/pageState.js @@ -0,0 +1,89 @@ +// The state that the validator and the playground share: the document, and +// what the playground adds to it. Each page writes it in the fragment of its +// URL, see permalink.js, and in the link of the menu to the other page, that +// opens with the same document. +// +// A state too long for a link is kept in the session storage of the tab +// instead, and the fragment says so: the page still opens the other one, and +// reloads, but its link can not be shared. + +import { decodeState, shareableFragment } from "./permalink.js"; + +// The fragment of a state that is in the session storage +const LOCAL = "local"; +const STORAGE_KEY = "structured-data-state"; + +// The links of the menu that carry the state +const LINKS = "a[data-state-link]"; + +let lastWrite = 0; + +/** + * Resolves with the state the page is opened with, or null when there is none. + * Nothing in it is to be trusted: a fragment is written by anyone. + */ +export async function readState() { + if (location.hash !== `#${LOCAL}`) { + return decodeState(location.hash); + } + + try { + const state = JSON.parse(sessionStorage.getItem(STORAGE_KEY)); + + return state !== null && typeof state === "object" && !Array.isArray(state) ? state : null; + } catch { + // No storage, or not a state + return null; + } +} + +/** + * The "#" and the fragment of a state: the one of a link when it is given, the + * one that says the state is in the session storage, where it is put, or + * nothing when it can be in neither. + */ +function hashOf(state, fragment) { + if (fragment !== null) { + return `#${fragment}`; + } + + try { + sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state)); + + return `#${LOCAL}`; + } catch { + // No storage, or no room in it + return ""; + } +} + +/** + * Resolves with the URL that opens a page with a state. + */ +export async function stateUrl(page, state) { + return page + hashOf(state, await shareableFragment(state)); +} + +/** + * Writes the state of the page in its URL, and in the links of its menu. + * Resolves with whether a link can hold it, or with null when another state was + * written meanwhile. + */ +export async function writeState(state) { + const write = ++lastWrite; + const fragment = await shareableFragment(state); + + if (write !== lastWrite) { + return null; + } + + const hash = hashOf(state, fragment); + + history.replaceState(null, "", hash || location.pathname + location.search); + + for (const link of document.querySelectorAll(LINKS)) { + link.hash = hash; + } + + return fragment !== null; +} diff --git a/website/assets/permalink.js b/website/assets/permalink.js new file mode 100644 index 000000000..f61fe45d4 --- /dev/null +++ b/website/assets/permalink.js @@ -0,0 +1,122 @@ +// The state of a page, in the fragment of its URL, without the DOM: a link to +// the page opens it as it is. pageState.js wires it to the pages of the +// validator and of the playground, tests/permalink.test.mjs tests it in node. +// +// The fragment is a version, then the state as JSON, compressed and written in +// base64url: "1" when the browser compresses (deflate), "0" when it can not. +// +// The state of the validator is its "document". The playground has one too, +// among others: the fragment of a page opens the other one as well. + +import { ALGORITHMS, normalizeOptions } from "./jsonLd.js"; + +// What a fragment may decompress to: a few bytes can inflate to gigabytes +const MAX_STATE_SIZE = 4 * 1024 * 1024; + +// A longer fragment is not written in the URL: a browser, or what the link is +// pasted in, cuts it +export const MAX_FRAGMENT_LENGTH = 32_000; + +/** + * The state as the playground expects it, whatever is given: a fragment is + * written by anyone. + */ +export function normalizeState(given) { + const text = (value) => (typeof value === "string" ? value : ""); + + return { + algorithm: ALGORITHMS.includes(given?.algorithm) ? given.algorithm : "expand", + document: text(given?.document), + nquads: text(given?.nquads), + context: text(given?.context), + frame: text(given?.frame), + options: normalizeOptions(given?.options), + }; +} + +/** + * Resolves with the fragment of a state, without its "#". + */ +export async function encodeState(state) { + const bytes = new TextEncoder().encode(JSON.stringify(state)); + + if (typeof CompressionStream === "undefined") { + return "0" + toBase64Url(bytes); + } + + return "1" + toBase64Url(await through(bytes, new CompressionStream("deflate-raw"))); +} + +/** + * Resolves with the fragment of a state that a link can hold, without its "#", + * or null when it is too long for one. + */ +export async function shareableFragment(state) { + const fragment = await encodeState(state); + + return fragment.length > MAX_FRAGMENT_LENGTH ? null : fragment; +} + +/** + * Resolves with the state of a fragment, as it was written, or null when it + * holds none. Nothing in it is to be trusted: a fragment is written by anyone. + */ +export async function decodeState(fragment) { + const encoded = fragment.replace(/^#/, ""); + + try { + let bytes = fromBase64Url(encoded.slice(1)); + + if (encoded[0] === "1") { + bytes = await through(bytes, new DecompressionStream("deflate-raw")); + } else if (encoded[0] !== "0") { + return null; + } + + const state = JSON.parse(new TextDecoder().decode(bytes)); + + return state !== null && typeof state === "object" && !Array.isArray(state) ? state : null; + } catch { + // Not a state: a fragment of another kind, or one cut by a mail client + return null; + } +} + +async function through(bytes, stream) { + const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader(); + const chunks = []; + let size = 0; + + for (;;) { + const { done, value } = await reader.read(); + + if (done) { + return new Uint8Array(await new Blob(chunks).arrayBuffer()); + } + + size += value.length; + + if (size > MAX_STATE_SIZE) { + await reader.cancel(); + + throw new RangeError("The state is too large."); + } + + chunks.push(value); + } +} + +function toBase64Url(bytes) { + let binary = ""; + + // Not all at once: the arguments of a call are limited + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} + +function fromBase64Url(encoded) { + return Uint8Array.from(atob(encoded.replaceAll("-", "+").replaceAll("_", "/")), (character) => character.charCodeAt(0)); +} diff --git a/website/assets/php.js b/website/assets/php.js index 11bc4ecb4..9a69d98b3 100644 --- a/website/assets/php.js +++ b/website/assets/php.js @@ -1,24 +1,21 @@ -// The validator in PHP WebAssembly, without the DOM: app.js wires it to the -// page, tests/page.test.mjs tests it in node. +// The library in PHP WebAssembly, without the DOM: the controllers of the +// validator and of the playground wire it to their page, tests/page.test.mjs +// and tests/playground.test.mjs test it in node. // Built next to this module, in public/build: see .castor/website.php import createPhp from "./php-web.mjs"; -// Where .castor/website.php embeds it +// Where .castor/website.php embeds them const AUDIT_SCRIPT = "/app/bin/audit.php"; +const PLAYGROUND_SCRIPT = "/app/bin/playground.php"; -// Loading starts with the page, the first audit waits for it +// Loading starts with the page, the first run waits for it const loadingPhp = createPhp(); -/** - * Resolves with what bin/audit.php answers: the { html } of the result, or the - * { error } that says why the document is not audited. - */ -export async function audit({ body, mergeSharedIdentifiers, allowPendingVocabulary }) { +// Both scripts read their request on stdin, and answer on stdout, as JSON +async function run(script, request) { const php = await loadingPhp; - const { exitCode, stdout, stderr } = await php.runFile(AUDIT_SCRIPT, { - stdin: JSON.stringify({ allowPendingVocabulary, body, mergeSharedIdentifiers }), - }); + const { exitCode, stdout, stderr } = await php.runFile(script, { stdin: JSON.stringify(request) }); if (stderr) { console.error(stderr); @@ -29,3 +26,20 @@ export async function audit({ body, mergeSharedIdentifiers, allowPendingVocabula return JSON.parse(stdout); } + +/** + * Resolves with what bin/audit.php answers: the { counts, html } of the result, + * or the { error } that says why the document is not audited. + */ +export function audit({ body, mergeSharedIdentifiers, allowPendingVocabulary }) { + return run(AUDIT_SCRIPT, { allowPendingVocabulary, body, mergeSharedIdentifiers }); +} + +/** + * Resolves with what bin/playground.php answers: the { output } of a JSON-LD + * algorithm, the { error } that says why there is none, or the { missing } + * documents to fetch first. assets/jsonLd.js fetches them, and asks again. + */ +export function runPlayground({ algorithm, document, context, frame, options, documents }) { + return run(PLAYGROUND_SCRIPT, { algorithm, context, document, documents, frame, options }); +} diff --git a/website/assets/playground.js b/website/assets/playground.js new file mode 100644 index 000000000..bbfde62bf --- /dev/null +++ b/website/assets/playground.js @@ -0,0 +1,8 @@ +// The page of the playground, public/playground/index.html: the JSON-LD +// algorithms of the library, run on what the visitor types. + +import { Application } from "@hotwired/stimulus"; +import PlaygroundController from "./controllers/playground_controller.js"; + +const app = Application.start(); +app.register("playground", PlaygroundController); diff --git a/website/assets/playgroundExamples.js b/website/assets/playgroundExamples.js new file mode 100644 index 000000000..eb8c9bbee --- /dev/null +++ b/website/assets/playgroundExamples.js @@ -0,0 +1,190 @@ +// The examples of the playground. Each one opens the tab of its "algorithm". +// The ones made of a JSON-LD "document" come with the "context" and the "frame" +// of the tabs that need one: every tab shows something for every example, see +// tests/playground.test.mjs. + +const person = { + label: "Person", + algorithm: "expand", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/people/ada", + "@type": "Person", + "name": "Ada Lovelace", + "jobTitle": "Mathematician", + "birthDate": "1815-12-10", + "knows": { + "@id": "https://example.com/people/charles", + "@type": "Person", + "name": "Charles Babbage" + } +}`, + context: `{ + "@context": { + "schema": "http://schema.org/", + "Person": "schema:Person", + "name": "schema:name", + "knows": "schema:knows" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Person", + "knows": { + "@embed": "@never" + } +}`, +}; + +const event = { + label: "Event", + algorithm: "compact", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/events/php-meetup", + "@type": "Event", + "name": "PHP meetup", + "startDate": "2026-12-03T19:00:00+01:00", + "eventAttendanceMode": "https://schema.org/OfflineEventAttendanceMode", + "location": { + "@type": "Place", + "name": "JoliCode", + "address": { + "@type": "PostalAddress", + "addressLocality": "Paris", + "addressCountry": "FR" + } + } +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/", + "title": "name", + "starts": { + "@id": "startDate", + "@type": "DateTime" + }, + "where": "location" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Place" +}`, +}; + +const product = { + label: "Product", + algorithm: "toRdf", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/products/mug", + "@type": "Product", + "name": "Yellow mug", + "sku": "MUG-001", + "brand": { + "@type": "Brand", + "name": "JoliCode" + }, + "offers": { + "@type": "Offer", + "price": 12.5, + "priceCurrency": "EUR", + "availability": "https://schema.org/InStock" + } +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Offer" +}`, +}; + +// What a SEO plugin writes: flat nodes that refer to each other, which a frame +// turns into the tree of the article +const articleGraph = { + label: "Article graph, framed", + algorithm: "frame", + document: `{ + "@context": "https://schema.org", + "@graph": [ + { + "@id": "https://example.com/#organization", + "@type": "Organization", + "name": "Example", + "url": "https://example.com/" + }, + { + "@id": "https://example.com/#/people/ada", + "@type": "Person", + "name": "Ada Lovelace" + }, + { + "@id": "https://example.com/blog/hello/#article", + "@type": "Article", + "headline": "Hello world", + "datePublished": "2026-11-02", + "author": { + "@id": "https://example.com/#/people/ada" + }, + "publisher": { + "@id": "https://example.com/#organization" + } + } + ] +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Article" +}`, +}; + +// Its context is not schema.org, that the library ships: the browser fetches it +const activity = { + label: "Activity, with a remote context", + algorithm: "expand", + document: `{ + "@context": "https://www.w3.org/ns/activitystreams", + "id": "https://example.com/notes/1", + "type": "Note", + "attributedTo": "https://example.com/people/ada", + "content": "A remote context, fetched by your browser.", + "published": "2026-11-23T10:00:00Z" +}`, + context: `{ + "@context": { + "as": "https://www.w3.org/ns/activitystreams#", + "content": "as:content" + } +}`, + frame: `{ + "@context": "https://www.w3.org/ns/activitystreams", + "type": "Note" +}`, +}; + +const nquads = { + label: "N-Quads", + algorithm: "fromRdf", + nquads: ` . + "Ada Lovelace" . + "1815-12-10"^^ . + . + . + "Charles Babbage" . +`, +}; + +export const examples = { person, event, product, articleGraph, activity, nquads }; + +// What the playground opens with +export const DEFAULT_EXAMPLE = "person"; diff --git a/website/assets/styles/app.css b/website/assets/styles/app.css index 3eb3a051d..09e8f6569 100644 --- a/website/assets/styles/app.css +++ b/website/assets/styles/app.css @@ -56,6 +56,36 @@ @apply inline-flex min-h-10 cursor-pointer items-center gap-2 rounded-full border border-gray-300 bg-white px-4 text-[13px] font-medium shadow-sm transition hover:-translate-y-px hover:border-gray-900 hover:shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; } +/* The menu of the pages: the highlighter underlines the current one */ +.site-nav-link { + @apply inline-flex min-h-9 items-center font-medium text-gray-700 hover:text-gray-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; + + &[aria-current="page"] { + @apply text-gray-950; + box-shadow: inset 0 -3px 0 var(--color-joli); + } +} + +/* The counts and the actions of the result of the validator: they stay above the entities, that scroll under them */ +.result-toolbar { + @apply relative z-10 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 rounded-2xl border border-gray-200 bg-white px-4 py-2.5 lg:sticky lg:top-5; + + /* What scrolls is not seen between the top of the window and the toolbar: the gap above its border */ + &::before { + @apply pointer-events-none absolute -inset-x-px -top-5.25 hidden h-5 bg-gray-50 lg:block; + content: ""; + } +} + +/* The algorithms of the playground */ +.playground-tab { + @apply min-h-9 cursor-pointer rounded-lg px-3 text-[13px] font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; + + &[aria-selected="true"] { + @apply bg-gray-900 text-white; + } +} + .cm-editor { @apply h-full text-[13px]; diff --git a/website/assets/validator.js b/website/assets/validator.js new file mode 100644 index 000000000..8f528919d --- /dev/null +++ b/website/assets/validator.js @@ -0,0 +1,10 @@ +// The page of the validator, public/validator/index.html: audits the document +// it is opened with, and shows the result, see controllers/result_controller.js. + +import { Application } from "@hotwired/stimulus"; +import HighlightController from "./controllers/highlight_controller.js"; +import ResultController from "./controllers/result_controller.js"; + +const app = Application.start(); +app.register("highlight", HighlightController); +app.register("result", ResultController); diff --git a/website/bin/audit.php b/website/bin/audit.php index 47423d7eb..439674647 100644 --- a/website/bin/audit.php +++ b/website/bin/audit.php @@ -10,8 +10,9 @@ */ // Run in the browser by PHP WebAssembly, see assets/php.js: the request is on -// stdin, and the answer on stdout, as JSON: the "html" of the result, or the -// "error" that says why the document is not audited. +// stdin, and the answer on stdout, as JSON: the "html" of the entities of the +// result and the one of their "counts", or the "error" that says why the +// document is not audited. The page holds the rest: its editor, its toolbar. use JoliCode\StructuredData\Audit\Item; use JoliCode\StructuredData\Mapper\MappedType; @@ -60,11 +61,11 @@ $twig->addExtension(new JsonLdExtension()); $twig->addExtension(new MarkdownExtension()); +// The items, not the blocks: with the merge on, the blocks sharing an +// identifier make one item, whose node carries the verdict. +$types = array_map(static fn (Item $item): MappedType => $item->getType(), $audit->getItems()); + echo json_encode([ - 'html' => $twig->render('result.html.twig', [ - 'body' => $body, - // The items, not the blocks: with the merge on, the blocks sharing an - // identifier make one item, whose node carries the verdict. - 'types' => array_map(static fn (Item $item): MappedType => $item->getType(), $audit->getItems()), - ]), + 'counts' => $twig->render('counts.html.twig', ['types' => $types]), + 'html' => $twig->render('result.html.twig', ['types' => $types]), ], \JSON_THROW_ON_ERROR); diff --git a/website/bin/playground.php b/website/bin/playground.php new file mode 100644 index 000000000..3d91a6a42 --- /dev/null +++ b/website/bin/playground.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +// Run in the browser by PHP WebAssembly, see assets/php.js: the request is on +// stdin, and the answer on stdout, as JSON. It is the "output" of the +// algorithm, with its "language", or the "error" that says why there is none, +// or the "missing" documents: PHP has no network here, so the page fetches +// them, and asks again with them, see assets/jsonLd.js. + +use JoliCode\StructuredData\JsonLd\Algorithms\Compact\Compactor; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; +use JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Website\JsonLd\PreloadedDocumentLoader; + +ini_set('display_errors', '0'); +ini_set('log_errors', '1'); + +require __DIR__ . '/../vendor/autoload.php'; + +// As bin/audit.php: the memory of the WebAssembly module does not grow. It is +// the size of everything the algorithm reads, the fetched documents too. +const MAX_REQUEST_SIZE = 2 * 1024 * 1024; + +const JSON_OUTPUT = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION | \JSON_THROW_ON_ERROR; + +const ALGORITHMS = ['expand', 'compact', 'flatten', 'frame', 'toRdf', 'fromRdf']; + +/** + * @var array{ + * algorithm: string, + * document: string, + * context?: string, + * frame?: string, + * options?: array, + * documents?: array, + * } $request + */ +$request = json_decode((string) file_get_contents('php://stdin'), true, flags: \JSON_THROW_ON_ERROR); + +$algorithm = $request['algorithm']; +$document = $request['document']; +$context = $request['context'] ?? ''; +$frame = $request['frame'] ?? ''; +$given = $request['options'] ?? []; +$documents = $request['documents'] ?? []; + +$answer = static function (array $answer): void { + echo json_encode($answer, \JSON_THROW_ON_ERROR); +}; + +// A context, or a frame: what is not JSON is said so, rather than taken for a URL +$isJson = static function (string $json): bool { + json_decode($json); + + return \JSON_ERROR_NONE === json_last_error(); +}; + +$size = strlen($document) + strlen($context) + strlen($frame) + array_sum(array_map(strlen(...), $documents)); + +$error = match (true) { + !in_array($algorithm, ALGORITHMS, true) => 'This algorithm is not known.', + '' === trim($document) => 'fromRdf' === $algorithm ? 'Please enter some N-Quads.' : 'Please enter a JSON-LD document.', + $size > MAX_REQUEST_SIZE => 'This document is too large to be processed.', + 'compact' === $algorithm && '' === trim($context) => 'Please enter the context to compact the document with.', + in_array($algorithm, ['compact', 'flatten'], true) && '' !== trim($context) && !$isJson($context) => 'The context is not valid JSON.', + 'frame' === $algorithm && '' === trim($frame) => 'Please enter the frame to frame the document with.', + 'frame' === $algorithm && !$isJson($frame) => 'The frame is not valid JSON.', + default => null, +}; + +if (null !== $error) { + $answer(['error' => $error]); + + return; +} + +$options = new ProcessorOptions( + base: '' === ($given['base'] ?? '') ? null : (string) $given['base'], + compactArrays: (bool) ($given['compactArrays'] ?? true), + compactToRelative: (bool) ($given['compactToRelative'] ?? true), + omitGraph: isset($given['omitGraph']) ? (bool) $given['omitGraph'] : null, + ordered: (bool) ($given['ordered'] ?? false), + produceGeneralizedRdf: (bool) ($given['produceGeneralizedRdf'] ?? false), + rdfDirection: '' === ($given['rdfDirection'] ?? '') ? null : (string) $given['rdfDirection'], + useNativeTypes: (bool) ($given['useNativeTypes'] ?? false), + useRdfType: (bool) ($given['useRdfType'] ?? false), +); + +$loader = new PreloadedDocumentLoader($documents); + +try { + $output = match ($algorithm) { + 'expand' => json_encode(new Expander(documentLoader: $loader)->expand($document, $options, encodeResult: false), JSON_OUTPUT), + 'compact' => json_encode(new Compactor(documentLoader: $loader)->compact($document, json_decode($context), $options, encodeResult: false), JSON_OUTPUT), + // It answers a string, that is not always indented + 'flatten' => json_encode(json_decode((string) new Flattener(documentLoader: $loader)->flatten($document, '' === trim($context) ? null : json_decode($context), $options)), JSON_OUTPUT), + 'frame' => json_encode(new Framer(documentLoader: $loader)->frame($document, $frame, $options, encodeResult: false), JSON_OUTPUT), + 'toRdf' => NQuadsSerializer::serialize(new ToRdfConverter(documentLoader: $loader)->toRdf($document, $options)), + 'fromRdf' => json_encode(new FromRdfConverter()->fromRdf($document, $options, encodeResult: false), JSON_OUTPUT), + }; +} catch (JsonLdException $exception) { + // The message of the library is the error code of the specification, and + // never says which URL failed. Here the URL comes from the document of the + // visitor, and is fetched by their browser: naming it tells nothing more. + $answer(match (true) { + [] !== $loader->getMissing() => ['missing' => $loader->getMissing()], + [] !== $loader->getUnreadable() => ['error' => sprintf('%s: %s is not a JSON document.', $exception->getMessage(), implode(', ', $loader->getUnreadable()))], + default => ['error' => $exception->getMessage()], + }); + + return; +} + +$answer([ + 'language' => 'toRdf' === $algorithm ? 'nquads' : 'json', + // What the page has to give again, the next time it asks + 'loaded' => $loader->getLoaded(), + 'output' => $output, +]); diff --git a/website/package.json b/website/package.json index 024f0578c..ffda8cfea 100644 --- a/website/package.json +++ b/website/package.json @@ -7,7 +7,7 @@ "build": "npm run build:fonts && npm run build:css && npm run build:js", "build:css": "tailwindcss --input assets/styles/app.css --output public/build/app.css --minify", "build:fonts": "mkdir -p public/build/files && cp node_modules/@fontsource-variable/inter/files/*-wght-normal.woff2 node_modules/@fontsource-variable/jetbrains-mono/files/*-wght-normal.woff2 node_modules/@fontsource-variable/space-grotesk/files/*-wght-normal.woff2 public/build/files/", - "build:js": "esbuild assets/app.js assets/php.js --bundle --splitting --format=esm --minify --outdir=public/build --external:./php-web.mjs" + "build:js": "esbuild assets/home.js assets/validator.js assets/playground.js assets/php.js --bundle --splitting --format=esm --minify --outdir=public/build --external:./php-web.mjs" }, "devDependencies": { "@codemirror/autocomplete": "6.20.4", diff --git a/website/public/index.html b/website/public/index.html index 5b5b4caf5..f3733f693 100644 --- a/website/public/index.html +++ b/website/public/index.html @@ -13,7 +13,9 @@ - + + +
@@ -23,7 +25,10 @@ Structured Data Validator -
+ + + diff --git a/website/public/validator/index.html b/website/public/validator/index.html new file mode 100644 index 000000000..d47f4d33f --- /dev/null +++ b/website/public/validator/index.html @@ -0,0 +1,177 @@ + + + + + + + Structured Data Validator, by JoliCode + + + + + + + + + + + +
+ +
+ + + Structured Data Validator + + +
+ + +
+ +
+
+
+ +
+ +
+ +
+ + + + +
+ + + + + + +
+ + + +
+ + + + + +
+ + + +
+ + +
+

Validating your document…

+
+
+
+
+ + diff --git a/website/src/JsonLd/PreloadedDocumentLoader.php b/website/src/JsonLd/PreloadedDocumentLoader.php new file mode 100644 index 000000000..d1ae41c16 --- /dev/null +++ b/website/src/JsonLd/PreloadedDocumentLoader.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Website\JsonLd; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\DocumentLoadingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LoadDocumentOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteDocument; + +/** + * Hands out the documents the page fetched: PHP WebAssembly has no network, the + * browser has. A document that is not there is remembered as missing, for the + * page to fetch it and run the algorithm again, see bin/playground.php. + */ +final class PreloadedDocumentLoader implements DocumentLoaderInterface +{ + /** @var list */ + private array $loaded = []; + + /** @var list */ + private array $missing = []; + + /** @var list */ + private array $unreadable = []; + + /** + * @param array $documents the body of each document, by URL + */ + public function __construct( + private readonly array $documents, + ) { + } + + public function load(string $url, LoadDocumentOptions $options = new LoadDocumentOptions()): RemoteDocument + { + if (!\array_key_exists($url, $this->documents)) { + $this->missing[] = $url; + + throw DocumentLoadingException::loadingFailed(); + } + + $document = json_decode($this->documents[$url]); + + if (!$document instanceof \stdClass && !\is_array($document)) { + $this->unreadable[] = $url; + + throw DocumentLoadingException::loadingFailed(); + } + + $this->loaded[] = $url; + + return new RemoteDocument($document, $url); + } + + public function getCacheNamespace(): string + { + return 'preloaded-' . hash('xxh128', serialize($this->documents)); + } + + /** + * The documents that were handed out. + * + * @return list + */ + public function getLoaded(): array + { + return array_values(array_unique($this->loaded)); + } + + /** + * The documents that were asked for, and that the page did not give. + * + * @return list + */ + public function getMissing(): array + { + return array_values(array_unique($this->missing)); + } + + /** + * The documents that the page gave, and that are not JSON. + * + * @return list + */ + public function getUnreadable(): array + { + return array_values(array_unique($this->unreadable)); + } +} diff --git a/website/templates/components/_type.html.twig b/website/templates/components/_type.html.twig index d784cd715..4f238e085 100644 --- a/website/templates/components/_type.html.twig +++ b/website/templates/components/_type.html.twig @@ -1,7 +1,7 @@ {% set errors = type.mergedErrors|filter(error => error.severity != 'warning') %} {% set warnings = type.mergedErrors|filter(error => error.severity == 'warning') %} -
+

{% if type.type is iterable %} diff --git a/website/templates/counts.html.twig b/website/templates/counts.html.twig new file mode 100644 index 000000000..3d51f5b32 --- /dev/null +++ b/website/templates/counts.html.twig @@ -0,0 +1,20 @@ +{# What the toolbar of the page of the validator says of the result: nothing, when no structured data is found #} +{% set errorCount = 0 %} +{% set warningCount = 0 %} +{% for type in types %} + {% set errorCount = errorCount + type.mergedErrors|filter(error => error.severity != 'warning')|length %} + {% set warningCount = warningCount + type.mergedErrors|filter(error => error.severity == 'warning')|length %} +{% endfor %} + +{% if types|length > 0 %} + {{ types|length }} {{ types|length > 1 ? 'entities' : 'entity' }} + {% if errorCount %} + {{ errorCount }} error{{ errorCount > 1 ? 's' }} + {% endif %} + {% if warningCount %} + {{ warningCount }} warning{{ warningCount > 1 ? 's' }} + {% endif %} + {% if not errorCount and not warningCount %} + Valid + {% endif %} +{% endif %} diff --git a/website/templates/result.html.twig b/website/templates/result.html.twig index b944b16a5..83d11e5df 100644 --- a/website/templates/result.html.twig +++ b/website/templates/result.html.twig @@ -1,159 +1,19 @@ -{% set errorCount = 0 %} -{% set warningCount = 0 %} +{# The entities of the result. The page of the validator, public/validator/index.html, shows them under its toolbar, next to the editor it holds: see assets/controllers/result_controller.js #} {% for type in types %} - {% set errorCount = errorCount + type.mergedErrors|filter(error => error.severity != 'warning')|length %} - {% set warningCount = warningCount + type.mergedErrors|filter(error => error.severity == 'warning')|length %} -{% endfor %} - -
- {# The same backdrop and logo as the homepage, see public/index.html #} -
-
- - - Structured Data Validator - - {% if types|length > 0 %} - {{ types|length }} {{ types|length > 1 ? 'entities' : 'entity' }} - {% if errorCount %} - {{ errorCount }} error{{ errorCount > 1 ? 's' }} - {% endif %} - {% if warningCount %} - {{ warningCount }} warning{{ warningCount > 1 ? 's' }} - {% endif %} - {% if not errorCount and not warningCount %} - Valid - {% endif %} - {% endif %} + {{ include('components/_type.html.twig', {type: type}) }} +{% else %} +
+
+ {{ include('@images/error.svg') }} + We could not extract structured data from the provided code.
-
- {% if types|length > 0 %} - - - - {% endif %} - -
- - - -
+
+

+ In order to add json-ld structured data to your pages, add a <script> tag: +

- - - -
-
- -
-
- {# A browser drops the line break that follows the -

- -
- -
- {% for type in types %} - {{ include('components/_type.html.twig', {type: type}) }} - {% else %} -
-
- {{ include('@images/error.svg') }} - We could not extract structured data from the provided code. -
- -
-

- In order to add json-ld structured data to your pages, add a <script> tag: -

- -
<script type="application/ld+json">
+            
<script type="application/ld+json">
 {
   "@context": "https://schema.org",
   "@type": "Organization",
@@ -168,9 +28,6 @@
   }
 }
 </script>
-
-
- {% endfor %} -
-
-
+

+
+{% endfor %} diff --git a/website/tests/loadUrl.test.mjs b/website/tests/loadUrl.test.mjs new file mode 100644 index 000000000..efa1145ee --- /dev/null +++ b/website/tests/loadUrl.test.mjs @@ -0,0 +1,122 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { loadUrl } from '../assets/loadUrl.js'; + +// Runs assets/loadUrl.js, what the "Load" button of the homepage runs, in +// node, with a fetch that answers what a website would. + +const UNREADABLE = /could not be read from your browser/; + +// The fetch of node is an accessor, that t.mock.method() does not replace +const fetches = (t, implementation) => { + const original = globalThis.fetch; + const fetch = t.mock.fn(implementation); + + globalThis.fetch = fetch; + t.after(() => { + globalThis.fetch = original; + }); + + return fetch; +}; + +const answer = (t, body, init = {}) => fetches(t, async () => new Response(body, init)); + +test('loads the page of a website that allows it', async (t) => { + const fetch = answer(t, '

Hello

', { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); + + assert.deepEqual(await loadUrl(' https://example.com/page '), { body: '

Hello

' }); + + const [url, options] = fetch.mock.calls[0].arguments; + assert.equal(url, 'https://example.com/page'); + assert.equal(options.credentials, 'omit'); +}); + +test('loads a JSON-LD document', async (t) => { + answer(t, '{"@type": "Thing"}', { headers: { 'Content-Type': 'application/ld+json' } }); + + assert.deepEqual(await loadUrl('https://example.com/thing.jsonld'), { body: '{"@type": "Thing"}' }); +}); + +test('asks for a page or a JSON-LD document, unless told what to ask for', async (t) => { + const fetch = answer(t, '{}', { headers: { 'Content-Type': 'application/ld+json' } }); + + await loadUrl('https://example.com/'); + await loadUrl('https://example.com/context', { accept: 'application/ld+json' }); + + assert.match(fetch.mock.calls[0].arguments[1].headers.Accept, /^text\/html,application\/ld\+json/); + assert.equal(fetch.mock.calls[1].arguments[1].headers.Accept, 'application/ld+json'); +}); + +test('decodes the page with the charset of its Content-Type', async (t) => { + answer(t, Buffer.from('

café

', 'latin1'), { headers: { 'Content-Type': 'text/html; charset=ISO-8859-1' } }); + + assert.deepEqual(await loadUrl('https://example.com/'), { body: '

café

' }); +}); + +test('decodes the page with the charset of its meta element', async (t) => { + const page = '

café

'; + answer(t, Buffer.from(page, 'latin1'), { headers: { 'Content-Type': 'text/html' } }); + + assert.deepEqual(await loadUrl('https://example.com/'), { body: page }); +}); + +test('reads the page as UTF-8 when its charset is unknown', async (t) => { + answer(t, '

café

', { headers: { 'Content-Type': 'text/html; charset=nope' } }); + + assert.deepEqual(await loadUrl('https://example.com/'), { body: '

café

' }); +}); + +for (const url of ['', 'jolicode.com', 'ftp://example.com/page', 'javascript:alert(1)', 'file:///etc/hosts']) { + test(`refuses "${url}" without fetching it`, async (t) => { + const fetch = answer(t, ''); + + assert.match((await loadUrl(url)).error, /starting with http/); + assert.equal(fetch.mock.callCount(), 0); + }); +} + +test('says that the page can not be read, when the website does not allow it', async (t) => { + // What fetch does of a CORS refusal, and of a network failure as well + fetches(t, async () => { + throw new TypeError('Failed to fetch'); + }); + + assert.match((await loadUrl('https://example.com/')).error, UNREADABLE); +}); + +test('says that the page can not be read, when its download fails', async (t) => { + const body = new ReadableStream({ + start(controller) { + controller.error(new TypeError('terminated')); + }, + }); + answer(t, body, { headers: { 'Content-Type': 'text/html' } }); + + assert.match((await loadUrl('https://example.com/')).error, UNREADABLE); +}); + +test('reports the HTTP status of a page that is not found', async (t) => { + answer(t, 'Not found', { status: 404, headers: { 'Content-Type': 'text/html' } }); + + assert.deepEqual(await loadUrl('https://example.com/nope'), { error: 'This page answered with the HTTP status 404.' }); +}); + +test('refuses what is neither a page nor a JSON document', async (t) => { + answer(t, new Uint8Array(8), { headers: { 'Content-Type': 'image/png' } }); + + assert.deepEqual(await loadUrl('https://example.com/logo.png'), { error: 'This URL is neither a HTML page nor a JSON document.' }); +}); + +test('refuses a document that says it is too large, without downloading it', async (t) => { + answer(t, '

Hello

', { headers: { 'Content-Type': 'text/html', 'Content-Length': String(2 * 1024 * 1024 + 1) } }); + + assert.deepEqual(await loadUrl('https://example.com/'), { error: 'This document is too large to be validated.' }); +}); + +test('refuses a document that is too large', async (t) => { + answer(t, new Uint8Array(2 * 1024 * 1024 + 1), { headers: { 'Content-Type': 'text/html' } }); + + assert.deepEqual(await loadUrl('https://example.com/'), { error: 'This document is too large to be validated.' }); +}); diff --git a/website/tests/page.test.mjs b/website/tests/page.test.mjs index 6f4a1f49d..4d7ddd1d9 100644 --- a/website/tests/page.test.mjs +++ b/website/tests/page.test.mjs @@ -1,61 +1,66 @@ import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; import { test } from 'node:test'; import { examples } from '../assets/examples.js'; import { audit } from '../public/build/php.js'; -// Runs assets/php.js, as the page does, in node, on what "castor website:build" +// Runs assets/php.js, as the page of the validator does, in node, on what "castor website:build" // built. Run with "castor website:check": fetch-files.mjs of php-wasm-builder // lets node fetch the .wasm file. const settings = { allowPendingVocabulary: true, mergeSharedIdentifiers: true }; +// What a part of the result reads as, without its tags +const text = (html) => html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); + test('audits a valid document', async () => { - const { html } = await audit({ + const { counts, html } = await audit({ ...settings, body: '{"@context": "https://schema.org", "@type": "Organization", "name": "JoliCode", "url": "https://jolicode.com"}', }); assert.match(html, /]*>\s*Organization\s+]*>“JoliCode”<\/span>/); - assert.match(html, />Valid { - const { html } = await audit({ + const { counts, html } = await audit({ ...settings, body: '', }); - assert.match(html, /1 error/); + assert.match(text(counts), /^1 entity 1 error/); assert.match(html, /data-result-severity="error"/); assert.match(html, /data-start="2:/); }); -test('keeps the document as it is, in the editor', async () => { - const body = '\n{"@context": "https://schema.org", "@type": "Thing", "name": " & co"}'; - const { html } = await audit({ ...settings, body }); +test('says when there is no structured data', async () => { + const { counts, html } = await audit({ ...settings, body: '

Hello

' }); - assert.ok(html.includes(`data-result-target="codemirror">\n\n{"@context"`)); - assert.ok(html.includes('<b> & co')); + assert.match(html, /We could not extract structured data/); + assert.doesNotMatch(html, /data-result-target="entity"/); + assert.equal(text(counts), ''); }); -test('says when there is no structured data', async () => { - const { html } = await audit({ ...settings, body: '

Hello

' }); +test('renders the entities alone, for the page of the validator that holds the editor and the toolbar', async () => { + const { counts, html } = await audit({ ...settings, body: '{"@context": "https://schema.org", "@type": "Thing"}' }); - assert.match(html, /We could not extract structured data/); - assert.doesNotMatch(html, /data-result-target="expandButton"/); - assert.doesNotMatch(html, /data-result-target="showDescriptions"/); + assert.match(html, /^\s*]*data-result-target="entity"/); + + for (const part of [counts, html]) { + assert.doesNotMatch(part, / { - const { html } = await audit({ - ...settings, - body: '{"@context": "https://schema.org", "@type": "Organization", "name": "JoliCode"}', - }); +test('finds, in the page of the validator, what the result controller fills and reads', async () => { + const page = await readFile(new URL('../public/validator/index.html', import.meta.url), 'utf8'); + + assert.match(page, /data-controller="result"/); - assert.match(html, /data-result-target="expandButton"[^>]*>\s*Expand all\s*1 entity2 entities1 entity2 entities { diff --git a/website/tests/permalink.test.mjs b/website/tests/permalink.test.mjs new file mode 100644 index 000000000..d73708436 --- /dev/null +++ b/website/tests/permalink.test.mjs @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { defaultOptions } from '../assets/jsonLd.js'; +import { MAX_FRAGMENT_LENGTH, decodeState, encodeState, normalizeState, shareableFragment } from '../assets/permalink.js'; +import { examples } from '../assets/playgroundExamples.js'; + +// Runs assets/permalink.js, what writes the state of the validator and of the +// playground in the fragment of their URL, in node. + +const state = normalizeState({ + ...examples.person, + nquads: examples.nquads.nquads, + options: { base: 'https://example.com/', ordered: true, omitGraph: false, rdfDirection: 'i18n-datatype' }, +}); + +test('reads back the state it writes', async () => { + const fragment = await encodeState(state); + + assert.match(fragment, /^1[\w-]+$/); + assert.deepEqual(await decodeState(`#${fragment}`), state); +}); + +test('writes a state shorter than its documents', async () => { + assert.ok((await encodeState(state)).length < JSON.stringify(state).length); +}); + +test('reads a state that is not compressed', async () => { + const fragment = '0' + Buffer.from(JSON.stringify(state)).toString('base64url'); + + assert.deepEqual(await decodeState(fragment), state); +}); + +test('keeps what is not ASCII', async () => { + const document = '{"name": "café ☕ 日本語"}'; + + assert.equal((await decodeState(await encodeState({ document }))).document, document); +}); + +test('reads the state of the validator, that is a lone document, as it is', async () => { + const page = ''; + + assert.deepEqual(await decodeState(await encodeState({ document: page })), { document: page }); +}); + +test('completes the state of the validator, for the playground', async () => { + assert.deepEqual(normalizeState(await decodeState(await encodeState({ document: '{}' }))), { + algorithm: 'expand', + document: '{}', + nquads: '', + context: '', + frame: '', + options: defaultOptions(), + }); +}); + +test('takes nothing it does not know from a state, for the playground', async () => { + const fragment = await encodeState({ + algorithm: 'canonize', + document: ['not', 'a', 'string'], + options: { base: 1, ordered: 'yes', omitGraph: 'no', processingMode: '1.0', unknown: true }, + unknown: true, + }); + + assert.deepEqual(normalizeState(await decodeState(fragment)), normalizeState({})); +}); + +test('gives no fragment to a state that is too long for a link', async () => { + // Random bytes do not compress + const document = Buffer.from(crypto.getRandomValues(new Uint8Array(MAX_FRAGMENT_LENGTH))).toString('base64'); + + assert.equal(await shareableFragment({ document }), null); + assert.equal(await shareableFragment(state), await encodeState(state)); +}); + +for (const fragment of ['', '#', '#section', '1not-deflate', '0not-json', '1', '#0bnVsbA', '#0WzFd']) { + test(`reads no state in "${fragment}"`, async () => { + assert.equal(await decodeState(fragment), null); + }); +} + +test('refuses a state that inflates too much', async () => { + const fragment = await encodeState({ document: ' '.repeat(5 * 1024 * 1024) }); + + assert.ok(fragment.length < 10_000); + assert.equal(await decodeState(fragment), null); +}); diff --git a/website/tests/playground.test.mjs b/website/tests/playground.test.mjs new file mode 100644 index 000000000..8dbb90843 --- /dev/null +++ b/website/tests/playground.test.mjs @@ -0,0 +1,242 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { ALGORITHMS, MAX_DOCUMENTS, createJsonLdProcessor } from '../assets/jsonLd.js'; +import { examples } from '../assets/playgroundExamples.js'; +import { runPlayground } from '../public/build/php.js'; + +// Runs assets/jsonLd.js, as the playground does, in node, on what +// "castor website:build" built: bin/playground.php in PHP WebAssembly. Run with +// "castor website:check". Nothing is fetched: "load" answers what a website would. + +const person = '{"@context": "https://schema.org", "@id": "https://example.com/ada", "@type": "Person", "name": "Ada"}'; + +// The contexts of a website: the body of each URL +const website = (pages) => async (url) => (url in pages ? { body: pages[url] } : { error: 'This page answered with the HTTP status 404.' }); + +// A processor, the URLs it loads, and the number of times it runs PHP +const processor = (load = website({})) => { + const loaded = []; + const counts = { runs: 0 }; + + const process = createJsonLdProcessor({ + run: (request) => { + counts.runs++; + + return runPlayground(request); + }, + load: (url) => { + loaded.push(url); + + return load(url); + }, + }); + + return { process, loaded, counts }; +}; + +const output = async (request, load) => { + const answer = await processor(load).process(request); + + assert.equal(answer.error, undefined); + + return 'json' === answer.language ? JSON.parse(answer.output) : answer.output; +}; + +test('expands a document', async () => { + assert.deepEqual(await output({ algorithm: 'expand', document: person }), [ + { '@id': 'https://example.com/ada', '@type': ['http://schema.org/Person'], 'http://schema.org/name': [{ '@value': 'Ada' }] }, + ]); +}); + +test('compacts a document with a context', async () => { + const context = '{"@context": {"schema": "http://schema.org/", "name": "schema:name"}}'; + + assert.deepEqual(await output({ algorithm: 'compact', document: person, context }), { + '@context': { schema: 'http://schema.org/', name: 'schema:name' }, + '@id': 'https://example.com/ada', + '@type': 'schema:Person', + name: 'Ada', + }); +}); + +test('flattens a document, and compacts it when there is a context', async () => { + const document = '{"@context": "https://schema.org", "@id": "https://example.com/ada", "knows": {"@id": "https://example.com/charles", "name": "Charles"}}'; + + assert.deepEqual(await output({ algorithm: 'flatten', document }), [ + { '@id': 'https://example.com/ada', 'http://schema.org/knows': [{ '@id': 'https://example.com/charles' }] }, + { '@id': 'https://example.com/charles', 'http://schema.org/name': [{ '@value': 'Charles' }] }, + ]); + assert.deepEqual(await output({ algorithm: 'flatten', document, context: '{"@context": {"@vocab": "http://schema.org/"}}' }), { + '@context': { '@vocab': 'http://schema.org/' }, + '@graph': [ + { '@id': 'https://example.com/ada', knows: { '@id': 'https://example.com/charles' } }, + { '@id': 'https://example.com/charles', name: 'Charles' }, + ], + }); +}); + +test('frames a document', async () => { + const framed = await output({ algorithm: 'frame', document: examples.articleGraph.document, frame: examples.articleGraph.frame }); + + assert.equal(framed.type, 'Article'); + assert.equal(framed.author.name, 'Ada Lovelace'); + assert.equal(framed.publisher.name, 'Example'); +}); + +test('deserializes a document to RDF, as N-Quads', async () => { + assert.equal( + await output({ algorithm: 'toRdf', document: person }), + ' .\n' + + ' "Ada" .\n', + ); +}); + +test('serializes N-Quads as a document', async () => { + const document = ' "36"^^ .\n'; + + assert.deepEqual(await output({ algorithm: 'fromRdf', document }), [ + { '@id': 'https://example.com/ada', 'http://schema.org/age': [{ '@value': '36', '@type': 'http://www.w3.org/2001/XMLSchema#integer' }] }, + ]); + assert.deepEqual(await output({ algorithm: 'fromRdf', document, options: { useNativeTypes: true } }), [ + { '@id': 'https://example.com/ada', 'http://schema.org/age': [{ '@value': 36 }] }, + ]); +}); + +test('gives the options to the algorithm', async () => { + const document = '{"@id": "ada", "http://schema.org/name": "Ada"}'; + + assert.equal((await output({ algorithm: 'expand', document, options: { base: 'https://example.com/people/' } }))[0]['@id'], 'https://example.com/people/ada'); + assert.ok('@graph' in (await output({ algorithm: 'frame', document: person, frame: '{"@context": "https://schema.org"}', options: { omitGraph: false } }))); +}); + +test('writes the output as it is read: indented, with its slashes and its accents', async () => { + const { output: written } = await processor().process({ algorithm: 'expand', document: '{"http://schema.org/name": "café"}' }); + + assert.equal(written, '[\n {\n "http://schema.org/name": [\n {\n "@value": "café"\n }\n ]\n }\n]'); +}); + +test('reports the error code of the specification', async () => { + assert.deepEqual(await processor().process({ algorithm: 'expand', document: '{"@context": {"term": {"@id": 1}}}' }), { error: 'invalid IRI mapping' }); +}); + +test('says what is missing, or is not what is expected', async () => { + const { process } = processor(); + const error = async (request) => (await process(request)).error; + + assert.equal(await error({ algorithm: 'expand', document: ' ' }), 'Please enter a JSON-LD document.'); + assert.equal(await error({ algorithm: 'expand', document: '{"@context": ' }), 'The JSON string could not be parsed.'); + assert.equal(await error({ algorithm: 'compact', document: person }), 'Please enter the context to compact the document with.'); + assert.equal(await error({ algorithm: 'compact', document: person, context: '{' }), 'The context is not valid JSON.'); + assert.equal(await error({ algorithm: 'frame', document: person }), 'Please enter the frame to frame the document with.'); + assert.equal(await error({ algorithm: 'frame', document: person, frame: '{' }), 'The frame is not valid JSON.'); + assert.equal(await error({ algorithm: 'fromRdf', document: ' ' }), 'Please enter some N-Quads.'); + assert.match(await error({ algorithm: 'fromRdf', document: 'nope' }), /N-Quads statement at line 1/); + assert.equal(await error({ algorithm: 'canonize', document: person }), 'This algorithm is not known.'); + assert.equal(await error({ algorithm: 'expand', document: ' '.repeat(2 * 1024 * 1024) + '{}' }), 'This document is too large to be processed.'); +}); + +test('reads the schema.org context without loading it', async () => { + const { process, loaded } = processor(); + + await process({ algorithm: 'expand', document: person }); + + assert.deepEqual(loaded, []); +}); + +test('loads the remote context of a document, once', async () => { + const { process, loaded, counts } = processor(website({ 'https://example.com/context': '{"@context": {"name": "http://schema.org/name"}}' })); + const request = { algorithm: 'expand', document: '{"@context": "https://example.com/context", "name": "Ada"}' }; + + assert.deepEqual(JSON.parse((await process(request)).output), [{ 'http://schema.org/name': [{ '@value': 'Ada' }] }]); + // Once to learn what is missing, once with it + assert.equal(counts.runs, 2); + + await process(request); + + // What the last run read is given at once + assert.equal(counts.runs, 3); + assert.deepEqual(loaded, ['https://example.com/context']); +}); + +test('loads the context that a remote context loads', async () => { + const { process, loaded } = processor(website({ + 'https://example.com/context': '{"@context": ["https://example.com/vocabulary", {"title": "name"}]}', + 'https://example.com/vocabulary': '{"@context": {"@vocab": "http://schema.org/"}}', + })); + + const answer = await process({ algorithm: 'expand', document: '{"@context": "https://example.com/context", "title": "Ada"}' }); + + assert.deepEqual(JSON.parse(answer.output), [{ 'http://schema.org/name': [{ '@value': 'Ada' }] }]); + assert.deepEqual(loaded, ['https://example.com/context', 'https://example.com/vocabulary']); +}); + +test('loads a document given as its URL', async () => { + assert.deepEqual(await output({ algorithm: 'expand', document: 'https://example.com/ada.jsonld' }, website({ 'https://example.com/ada.jsonld': person })), [ + { '@id': 'https://example.com/ada', '@type': ['http://schema.org/Person'], 'http://schema.org/name': [{ '@value': 'Ada' }] }, + ]); +}); + +test('names the remote context that can not be loaded', async () => { + const { process } = processor(); + + assert.deepEqual(await process({ algorithm: 'expand', document: '{"@context": "https://example.com/nope"}' }), { + error: 'https://example.com/nope could not be loaded. This page answered with the HTTP status 404.', + }); +}); + +test('names the remote context that is not JSON', async () => { + const { process } = processor(website({ 'https://example.com/page': '

Hello

' })); + + assert.deepEqual(await process({ algorithm: 'expand', document: '{"@context": "https://example.com/page"}' }), { + error: 'loading remote context failed: https://example.com/page is not a JSON document.', + }); +}); + +test('stops loading the contexts of a document that loads too many', async () => { + const { process, loaded } = processor(async () => ({ body: '{"@context": {}}' })); + // The library refuses more than 10 contexts in a row, see below: here each + // node has its own + const nodes = Array.from({ length: MAX_DOCUMENTS + 1 }, (_, index) => ({ '@context': `https://example.com/context/${index}` })); + + assert.deepEqual(await process({ algorithm: 'expand', document: JSON.stringify({ '@graph': nodes }) }), { + error: `This document loads more than ${MAX_DOCUMENTS} remote documents.`, + }); + assert.equal(loaded.length, MAX_DOCUMENTS); +}); + +test('leaves the contexts that load each other without an end to the library', async () => { + // Each context loads the next one + const { process } = processor(async (url) => ({ body: JSON.stringify({ '@context': `${url}1` }) })); + + assert.deepEqual(await process({ algorithm: 'expand', document: '{"@context": "https://example.com/context/"}' }), { + error: 'context overflow', + }); +}); + +// The context of the "activity" example, as short as it can be +const activityStreams = website({ + 'https://www.w3.org/ns/activitystreams': '{"@context": {"@vocab": "https://www.w3.org/ns/activitystreams#", "id": "@id", "type": "@type"}}', +}); + +for (const [name, example] of Object.entries(examples)) { + // The N-Quads are read by one algorithm, the documents by the others + for (const algorithm of ALGORITHMS.filter((algorithm) => ('fromRdf' === algorithm) === ('nquads' in example))) { + test(`runs "${algorithm}" on the "${name}" example`, async () => { + const { process } = processor(activityStreams); + const answer = await process({ ...example, algorithm, document: example.nquads ?? example.document }); + + assert.equal(answer.error, undefined); + assert.notEqual(answer.output.trim(), ''); + assert.notEqual(answer.output, '[]'); + assert.notEqual(answer.output, '{}'); + }); + } +} + +test('opens each example on an algorithm that reads it', () => { + for (const example of Object.values(examples)) { + assert.ok(ALGORITHMS.includes(example.algorithm)); + assert.equal('fromRdf' === example.algorithm, 'nquads' in example); + } +});