diff --git a/browser/json-viewer/CHANGELOG.md b/browser/json-viewer/CHANGELOG.md new file mode 100644 index 0000000..7a6a306 --- /dev/null +++ b/browser/json-viewer/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## 1.0.0 + +First release of JSON Viewer Veyra for Chrome. + +- JSON pages as a tree, with lazy drawing (200 items at a time) for big files. +- Exact big and exactly-written numbers. +- The path of every value, with copy path and copy value. +- Search with match stepping. +- Broken JSON: line, column, the line highlighted and the mistake explained. +- Raw (coloured, 2/4 spaces, tabs or one line) and Original views; copy and download. +- A page to paste JSON or open a file, from the toolbar button. +- Dark, light and automatic themes; the view, indent and theme are remembered. diff --git a/browser/json-viewer/LICENSE b/browser/json-viewer/LICENSE new file mode 100644 index 0000000..2a7d760 --- /dev/null +++ b/browser/json-viewer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Vikram Singh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/browser/json-viewer/PRIVACY.md b/browser/json-viewer/PRIVACY.md new file mode 100644 index 0000000..c4bcde8 --- /dev/null +++ b/browser/json-viewer/PRIVACY.md @@ -0,0 +1,12 @@ +# JSON Viewer Veyra: privacy policy + +Last updated: 25 November 2026 + +JSON Viewer Veyra does not collect, store, send or sell any personal data or browsing data. + +- **What it reads:** when a page you open is JSON, the extension reads that page's text in your browser to show it as a tree. It reads nothing on other pages. +- **What it stores:** your choice of view, indentation and theme, saved with Chrome's own extension storage (`chrome.storage.sync`), which Chrome may sync to your Google account if you have sync turned on. +- **What it sends:** nothing. The extension makes no network requests and has no analytics, advertising or tracking. +- **JSON you paste or open** on the extension's own page stays in that tab and is gone when you close it. + +Questions: hire@flightcoders.com · FlightCoders, https://flightcoders.com diff --git a/browser/json-viewer/README.md b/browser/json-viewer/README.md new file mode 100644 index 0000000..7ad181f --- /dev/null +++ b/browser/json-viewer/README.md @@ -0,0 +1,37 @@ +# JSON Viewer Veyra (Chrome extension) + +Open any JSON in Chrome and read it as a clear, searchable tree. + +![The JSON Viewer tree with a value selected and its path shown](store/1-tree.png) + +## What it does + +- **A tree you can read.** Open and close any level, with a count of keys and items. Small files open fully, big ones open the top level and show 200 items at a time, so a 10 MB response stays fast. +- **Exact numbers.** Long IDs like `9007199254740993123` and prices like `19.90` are shown exactly as the server sent them. Most viewers round them silently. +- **The path of every value.** Click a value to see `$.items[0].price`, and copy the path or the value. +- **Search.** Keys and values, with Enter and Shift+Enter to step through matches. Ctrl+F jumps to the search box. +- **Mistakes, explained.** Broken JSON shows the line and column, highlights the line, and says plainly what's wrong, like an extra comma before `}`. +- **Raw and Original views.** Formatted and coloured with 2 spaces, 4 spaces, tabs or one line, or the text exactly as the page sent it. +- **Copy and download.** The whole JSON or the selected value. +- **Paste or open a file.** Click the toolbar button to paste JSON or open a `.json` file. +- **Dark, light or automatic** theme. Your view, indent and theme are remembered. + +## Private and safe + +- Nothing is sent anywhere. No analytics, no account, no network requests. +- The page's data is only ever shown as text: a JSON document can't run code through the viewer, and only `http` and `https` links are made clickable. +- It only changes pages that are JSON (a JSON content type, or plain text that is JSON). Web pages are never touched. +- The only permission is `storage`, to remember your view, indent and theme. + +## Develop + +```console +npm test # the core: parsing, exact numbers, paths, search, error positions +npm run test:browser # loads the extension into Chromium with Playwright and checks real pages +npm run zip # release/json-viewer-veyra-.zip for the Chrome Web Store +node scripts/screenshots.mjs # store/ screenshots and the promo tile +``` + +To try it: open `chrome://extensions`, turn on **Developer mode**, click **Load unpacked** and pick this folder. + +Made by [FlightCoders](https://flightcoders.com), the team behind the [Veyra](https://veyraeditor.com) editor. MIT licensed. diff --git a/browser/json-viewer/STORE-LISTING.md b/browser/json-viewer/STORE-LISTING.md new file mode 100644 index 0000000..2f98c61 --- /dev/null +++ b/browser/json-viewer/STORE-LISTING.md @@ -0,0 +1,48 @@ +# Chrome Web Store listing: what to paste where + +Upload `release/json-viewer-veyra-1.0.0.zip` at https://chrome.google.com/webstore/devconsole (one-time developer fee: US$5). + +## Store listing tab + +**Description** + +> Open any JSON in Chrome and read it as a clear, searchable tree. +> +> • A tree you can read: open and close any level, with counts of keys and items. Big files stay fast. +> • Exact numbers: long IDs and values like 19.90 are shown exactly as sent, never rounded. +> • The path of every value: click a value to see $.items[0].price, and copy the path or the value. +> • Search keys and values, and step through the matches. +> • Broken JSON? See the line and column, with the line highlighted and the mistake explained, like an extra comma. +> • Raw view with colours and 2-space, 4-space, tab or one-line formatting, and the original text. +> • Copy or download the JSON or the selected value. +> • Paste JSON or open a file from the toolbar button. +> • Dark, light or automatic theme. +> +> Private: nothing is sent anywhere, and there is no tracking. It only changes pages that are JSON. + +**Category:** Developer Tools **Language:** English + +**Graphics** (in `store/`): icon `icons/icon-128.png`; screenshots `1-tree.png`, `2-search.png`, `3-raw.png`, `4-error.png`, `5-light.png` (1280×800); small promo tile `promo-440x280.png`. + +**Homepage URL:** https://veyraeditor.com/json-viewer +**Support URL:** https://github.com/fcopensource/veyraeditor/issues + +## Privacy practices tab + +**Single purpose** + +> Show JSON documents as a readable, searchable tree. + +**Permission justification** + +- `storage`: Remembers the user's chosen view (tree or raw), indentation and theme. +- Host permission (content script on all URLs): JSON can be opened from any website or API, so the content script checks each page's content type and only changes pages that are JSON. It never reads or changes other pages. + +**Remote code:** No, I am not using remote code. + +**Data usage:** tick nothing (it collects no user data), then tick the three certifications: +- I do not sell or transfer user data to third parties, outside of the approved use cases +- I do not use or transfer user data for purposes that are unrelated to my item's single purpose +- I do not use or transfer user data to determine creditworthiness or for lending purposes + +**Privacy policy URL:** https://veyraeditor.com/json-viewer/privacy diff --git a/browser/json-viewer/icons/icon-128.png b/browser/json-viewer/icons/icon-128.png new file mode 100644 index 0000000..6b6919e Binary files /dev/null and b/browser/json-viewer/icons/icon-128.png differ diff --git a/browser/json-viewer/icons/icon-16.png b/browser/json-viewer/icons/icon-16.png new file mode 100644 index 0000000..a411d0f Binary files /dev/null and b/browser/json-viewer/icons/icon-16.png differ diff --git a/browser/json-viewer/icons/icon-32.png b/browser/json-viewer/icons/icon-32.png new file mode 100644 index 0000000..2f0a6fc Binary files /dev/null and b/browser/json-viewer/icons/icon-32.png differ diff --git a/browser/json-viewer/icons/icon-48.png b/browser/json-viewer/icons/icon-48.png new file mode 100644 index 0000000..cfe893a Binary files /dev/null and b/browser/json-viewer/icons/icon-48.png differ diff --git a/browser/json-viewer/manifest.json b/browser/json-viewer/manifest.json new file mode 100644 index 0000000..6e5cac4 --- /dev/null +++ b/browser/json-viewer/manifest.json @@ -0,0 +1,24 @@ +{ + "manifest_version": 3, + "name": "JSON Viewer Veyra", + "short_name": "JSON Viewer", + "version": "1.0.0", + "description": "View JSON as a clear, searchable tree. Exact big numbers, the path of every value, errors with line numbers. Private and offline.", + "minimum_chrome_version": "114", + "icons": { "16": "icons/icon-16.png", "32": "icons/icon-32.png", "48": "icons/icon-48.png", "128": "icons/icon-128.png" }, + "action": { + "default_title": "JSON Viewer: paste or open JSON", + "default_icon": { "16": "icons/icon-16.png", "32": "icons/icon-32.png" } + }, + "background": { "service_worker": "src/background.js" }, + "permissions": ["storage"], + "content_scripts": [ + { + "matches": [""], + "js": ["src/core.js", "src/render.js", "src/content.js"], + "css": ["src/viewer.css"], + "run_at": "document_end" + } + ], + "homepage_url": "https://veyraeditor.com/json-viewer" +} diff --git a/browser/json-viewer/package.json b/browser/json-viewer/package.json new file mode 100644 index 0000000..5fb759a --- /dev/null +++ b/browser/json-viewer/package.json @@ -0,0 +1,13 @@ +{ + "name": "json-viewer-veyra", + "version": "1.0.0", + "private": true, + "description": "JSON Viewer Veyra, a Chrome extension: JSON pages as a readable, searchable tree.", + "license": "MIT", + "type": "commonjs", + "scripts": { + "test": "node --test test/core.test.mjs", + "test:browser": "node test/browser.test.mjs", + "zip": "node scripts/zip.mjs" + } +} diff --git a/browser/json-viewer/release/json-viewer-veyra-1.0.0.zip b/browser/json-viewer/release/json-viewer-veyra-1.0.0.zip new file mode 100644 index 0000000..a878627 Binary files /dev/null and b/browser/json-viewer/release/json-viewer-veyra-1.0.0.zip differ diff --git a/browser/json-viewer/scripts/screenshots.mjs b/browser/json-viewer/scripts/screenshots.mjs new file mode 100644 index 0000000..1648737 --- /dev/null +++ b/browser/json-viewer/scripts/screenshots.mjs @@ -0,0 +1,96 @@ +// Makes the Chrome Web Store screenshots (1280x800) and promo tile (440x280) from the real extension. +// Run: node scripts/screenshots.mjs (PLAYWRIGHT_PATH can point at a playwright package) +import http from "node:http"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const ext = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const out = path.join(ext, "store"); +fs.mkdirSync(out, { recursive: true }); +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_PATH || path.resolve(ext, "../../node_modules/playwright")); + +const api = `{ + "id": 9007199254740993123, + "status": "shipped", + "total": 149.90, + "currency": "EUR", + "customer": { "name": "Northwind Traders", "email": "orders@northwind.example", "website": "https://northwind.example" }, + "items": [ + { "sku": "KB-210", "title": "Mechanical keyboard", "qty": 1, "price": 89.90, "tags": ["hardware", "desk"] }, + { "sku": "MS-044", "title": "Wireless mouse", "qty": 2, "price": 30.00, "tags": ["hardware"] } + ], + "shipping": { "carrier": "DHL", "tracking": "JD014600006281230452", "eta": "2026-12-02", "address": { "city": "Berlin", "country": "DE" } }, + "gift": false, + "coupon": null +}`; +const broken = `{ + "name": "veyra-app", + "version": "1.4.0", + "scripts": { + "dev": "vite", + "build": "vite build", + }, + "dependencies": { "react": "^19.2.0" } +}`; +const pages = { "/orders/1042.json": api, "/package.json": broken }; +const server = http.createServer((req, res) => { + const body = pages[req.url]; + if (!body) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { "Content-Type": "application/json" }); res.end(body); +}); +await new Promise(r => server.listen(0, "127.0.0.1", r)); +const base = `http://127.0.0.1:${server.address().port}`; + +const profile = fs.mkdtempSync(path.join(os.tmpdir(), "vjv-shots-")); +const context = await chromium.launchPersistentContext(profile, { + channel: "chromium", headless: true, colorScheme: "dark", + args: [`--disable-extensions-except=${ext}`, `--load-extension=${ext}`], + viewport: { width: 1280, height: 800 }, +}); +try { + const page = await context.newPage(); + // 1. the tree, with a value selected and its path shown + await page.goto(base + "/orders/1042.json"); + await page.waitForSelector(".vjv-row"); + await page.locator(".vjv-row", { hasText: '"tracking"' }).click(); + await page.mouse.move(0, 0); + await page.screenshot({ path: path.join(out, "1-tree.png") }); + // 2. search + await page.fill(".vjv-search", "hardware"); + await page.waitForFunction(() => document.querySelector(".vjv-hits")?.textContent.includes("of")); + await page.screenshot({ path: path.join(out, "2-search.png") }); + // 3. raw, coloured + await page.fill(".vjv-search", ""); + await page.click(".vjv-tab >> text=Raw"); + await page.screenshot({ path: path.join(out, "3-raw.png") }); + await page.click(".vjv-tab >> text=Tree"); + // 4. a mistake, found + await page.goto(base + "/package.json"); + await page.waitForSelector(".vjv-error"); + await page.screenshot({ path: path.join(out, "4-error.png") }); + // 5. light theme + await page.goto(base + "/orders/1042.json"); + await page.waitForSelector(".vjv-row"); + await page.click("text=◐ Auto"); await page.click("text=● Dark"); + await page.locator(".vjv-row", { hasText: '"total"' }).click(); + await page.mouse.move(0, 0); + await page.screenshot({ path: path.join(out, "5-light.png") }); + + // the small promo tile, drawn as HTML + const tile = await context.newPage(); + await tile.setViewportSize({ width: 440, height: 280 }); + const icon = fs.readFileSync(path.join(ext, "icons", "icon-128.png")).toString("base64"); + await tile.setContent(` + +
JSON Viewer
+
A clear, searchable tree.
Exact numbers. Private.
`); + await tile.screenshot({ path: path.join(out, "promo-440x280.png") }); + console.log("Saved to", out, fs.readdirSync(out).join(", ")); +} finally { + await context.close(); server.close(); + try { fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* temp */ } +} diff --git a/browser/json-viewer/scripts/zip.mjs b/browser/json-viewer/scripts/zip.mjs new file mode 100644 index 0000000..c85312c --- /dev/null +++ b/browser/json-viewer/scripts/zip.mjs @@ -0,0 +1,45 @@ +// Builds release/json-viewer-veyra-.zip for the Chrome Web Store: the manifest, src/ and icons/ only. +// No dependencies: a small zip writer with Node's zlib. +import fs from "node:fs"; +import path from "node:path"; +import zlib from "node:zlib"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const manifest = JSON.parse(fs.readFileSync(path.join(root, "manifest.json"), "utf8")); +const files = ["manifest.json", ...["src", "icons"].flatMap(dir => fs.readdirSync(path.join(root, dir)).sort().map(f => `${dir}/${f}`))]; + +const table = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; }); +const crc32 = buf => { let c = 0xffffffff; for (const b of buf) c = table[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; +// A fixed date (2026-01-01), so the same files always make the same zip. +const DOS_TIME = 0, DOS_DATE = ((2026 - 1980) << 9) | (1 << 5) | 1; + +const locals = [], centrals = []; +let offset = 0; +for (const name of files) { + const data = fs.readFileSync(path.join(root, name)); + const packed = zlib.deflateRawSync(data, { level: 9 }); + const crc = crc32(data), nameBuf = Buffer.from(name); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0, 6); local.writeUInt16LE(8, 8); + local.writeUInt16LE(DOS_TIME, 10); local.writeUInt16LE(DOS_DATE, 12); local.writeUInt32LE(crc, 14); + local.writeUInt32LE(packed.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(nameBuf.length, 26); + locals.push(local, nameBuf, packed); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); central.writeUInt16LE(0, 8); central.writeUInt16LE(8, 10); + central.writeUInt16LE(DOS_TIME, 12); central.writeUInt16LE(DOS_DATE, 14); central.writeUInt32LE(crc, 16); + central.writeUInt32LE(packed.length, 20); central.writeUInt32LE(data.length, 24); central.writeUInt16LE(nameBuf.length, 28); + central.writeUInt32LE(offset, 42); + centrals.push(central, nameBuf); + offset += 30 + nameBuf.length + packed.length; +} +const centralSize = centrals.reduce((n, b) => n + b.length, 0); +const end = Buffer.alloc(22); +end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); +end.writeUInt32LE(centralSize, 12); end.writeUInt32LE(offset, 16); + +const out = path.join(root, "release", `json-viewer-veyra-${manifest.version}.zip`); +fs.mkdirSync(path.dirname(out), { recursive: true }); +fs.writeFileSync(out, Buffer.concat([...locals, ...centrals, end])); +console.log(`${path.relative(root, out)}: ${files.length} files, ${(fs.statSync(out).size / 1024).toFixed(1)} KB`); +console.log(files.map(f => " " + f).join("\n")); diff --git a/browser/json-viewer/src/background.js b/browser/json-viewer/src/background.js new file mode 100644 index 0000000..ff7ba0d --- /dev/null +++ b/browser/json-viewer/src/background.js @@ -0,0 +1,4 @@ +// JSON Viewer Veyra: the toolbar button opens the viewer page, to paste JSON or open a file. +chrome.action.onClicked.addListener(() => { + chrome.tabs.create({ url: chrome.runtime.getURL('src/viewer.html') }); +}); diff --git a/browser/json-viewer/src/content.js b/browser/json-viewer/src/content.js new file mode 100644 index 0000000..a2e7d4b --- /dev/null +++ b/browser/json-viewer/src/content.js @@ -0,0 +1,38 @@ +/* + * JSON Viewer Veyra: turns a page that is only JSON into the viewer. On every other page it stops at once: + * a web page is text/html, and the browser shows JSON as one
 and nothing else.
+ */
+(function () {
+  'use strict';
+  const V = window.VJV;
+  if (!V || document.documentElement.classList.contains('vjv-page')) return;
+  const type = (document.contentType || '').toLowerCase();
+  const jsonType = V.isJsonType(type);
+  if (!jsonType && type !== 'text/plain') return;
+  const body = document.body;
+  if (!body) return;
+  // Chrome shows a JSON response as 
text
, plus its own small "Pretty-print" box in newer versions. + const pre = body.querySelector(':scope > pre'); + if (!pre) return; + const builtIn = [...body.children].filter(e => e !== pre); + if (builtIn.some(e => !e.classList.contains('json-formatter-container'))) return; + const text = pre.textContent || ''; + if (text.length > 60 * 1024 * 1024) return; // over 60 MB: leave it to the browser + if (!jsonType && !V.looksLikeJson(text)) return; + const parsed = V.parse(text); + if (!parsed.ok && !jsonType) return; // plain text that only looked like JSON + + const KEY = 'vjvSettings'; + const storage = typeof chrome !== 'undefined' && chrome.storage && chrome.storage.sync; + const start = settings => { + pre.hidden = true; pre.style.display = 'none'; + for (const e of builtIn) e.style.display = 'none'; + document.documentElement.classList.add('vjv-page'); + const host = document.createElement('div'); + host.className = 'vjv-host'; + body.appendChild(host); + const name = decodeURIComponent((location.pathname.split('/').pop() || location.hostname || 'data').replace(/\.json$/i, '')); + V.mount(host, { text, parsed, settings, title: name, saveSettings: s => storage && storage.set({ [KEY]: s }) }); + }; + if (storage) storage.get(KEY).then(r => start(r && r[KEY]), () => start()); else start(); +})(); diff --git a/browser/json-viewer/src/core.js b/browser/json-viewer/src/core.js new file mode 100644 index 0000000..c93688c --- /dev/null +++ b/browser/json-viewer/src/core.js @@ -0,0 +1,245 @@ +/* + * JSON Viewer Veyra: the parts with no page in them. Parsing (with exact big numbers), paths, search, formatting. + * Runs in the browser (window.VJV) and in Node for the tests (require). + */ +(function (root, factory) { + const api = factory(); + if (typeof module === 'object' && module.exports) module.exports = api; + else root.VJV = Object.assign(root.VJV || {}, api); +})(typeof self !== 'undefined' ? self : this, function () { + 'use strict'; + + /** A number whose text JavaScript can't hold exactly, like 12345678901234567890, or one written differently, like 1.50. */ + class Num { + constructor(source) { this.source = source; } + toString() { return this.source; } + } + + /** Content types that hold JSON: application/json, text/json, application/ld+json, application/vnd.api+json, … */ + function isJsonType(contentType) { + const t = String(contentType || '').split(';')[0].trim().toLowerCase(); + return /^(application|text)\/(.+\+)?json$/.test(t) || t === 'application/x-json'; + } + + /** Text that could be JSON: starts and ends like an object or an array. */ + function looksLikeJson(text) { + const t = stripPrefix(text).body.trim(); + return (t.startsWith('{') && t.endsWith('}')) || (t.startsWith('[') && t.endsWith(']')); + } + + /** Takes off a byte-order mark and the anti-hijacking prefixes some APIs put before JSON, like )]}' and while(1); */ + function stripPrefix(text) { + let body = String(text); + if (body.charCodeAt(0) === 0xfeff) body = body.slice(1); + const m = body.match(/^\s*(\)\]\}',?|while\s*\(\s*1\s*\)\s*;|for\s*\(\s*;\s*;\s*\)\s*;)/); + if (m) return { body: body.slice(m[0].length), prefix: m[1] }; + return { body, prefix: '' }; + } + + /** + * The offset of the first mistake in JSON text, found by a small strict scanner (browsers don't always say where). + * Returns -1 if the text is valid JSON. + */ + function errorOffset(text) { + let i = 0; + const n = text.length; + class Stop { constructor(at) { this.at = at; } } + const fail = at => { throw new Stop(at); }; + const ws = () => { while (i < n && ' \t\n\r'.includes(text[i])) i++; }; + const word = w => { for (let k = 0; k < w.length; k++) if (text[i + k] !== w[k]) fail(i + k); i += w.length; }; + function str() { + i++; // the opening quote + while (i < n) { + const c = text[i]; + if (c === '"') { i++; return; } + if (c === '\\') { + const e = text[i + 1]; + if (e === 'u') { if (!/^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) fail(i); i += 6; continue; } + if (!'"\\/bfnrt'.includes(e) || e === undefined) fail(i); + i += 2; continue; + } + if (c < ' ') fail(i); + i++; + } + fail(n); + } + function num() { + const m = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(i, i + 400)); + if (!m) fail(i); + i += m[0].length; + } + function value() { + ws(); + const c = text[i]; + if (c === '{') { + i++; ws(); + if (text[i] === '}') { i++; return; } + for (;;) { + ws(); if (text[i] !== '"') fail(i); + str(); ws(); if (text[i] !== ':') fail(i); i++; + value(); ws(); + if (text[i] === ',') { i++; continue; } + if (text[i] === '}') { i++; return; } + fail(i); + } + } + if (c === '[') { + i++; ws(); + if (text[i] === ']') { i++; return; } + for (;;) { + value(); ws(); + if (text[i] === ',') { i++; continue; } + if (text[i] === ']') { i++; return; } + fail(i); + } + } + if (c === '"') return str(); + if (c === 't') return word('true'); + if (c === 'f') return word('false'); + if (c === 'n') return word('null'); + if (c === '-' || (c >= '0' && c <= '9')) return num(); + fail(i); + } + try { value(); ws(); return i < n ? i : -1; } catch (e) { if (e instanceof Stop) return Math.min(e.at, n); throw e; } + } + + /** A 1-based line and column for an offset in the text. */ + function lineColumn(text, offset) { + const before = text.slice(0, offset).split('\n'); + return { line: before.length, column: before[before.length - 1].length + 1 }; + } + + /** + * Parses JSON text. Numbers whose text would change in JavaScript (too big, too precise, or written like 1.50) + * are kept as Num with their exact text, using the source text the browser gives the reviver. + */ + function parse(text) { + const { body, prefix } = stripPrefix(text); + const trimmed = body.trim(); + if (!trimmed) return { ok: false, error: 'There is nothing here.', prefix }; + try { + const value = JSON.parse(trimmed, function (key, v, context) { + if (typeof v === 'number' && context && typeof context.source === 'string' && context.source !== String(v)) return new Num(context.source); + return v; + }); + return { ok: true, value, prefix }; + } catch (e) { + const lead = body.length - body.trimStart().length; + const at = errorOffset(trimmed); + const where = at >= 0 ? lineColumn(body, lead + at) : null; + const message = e.message.replace(/^JSON\.parse: /, '').replace(/,? ?".*" is not valid JSON$/s, '').replace(/ in JSON at position \d+.*$/s, ''); + return { ok: false, error: at >= 0 ? (hintAt(trimmed, at) || message) : message, where, prefix }; + } + } + + /** The everyday mistakes, said plainly: a comma before } or ], single quotes, keys without quotes, a missing comma. */ + function hintAt(text, at) { + const c = text[at]; + let b = at - 1; + while (b >= 0 && ' \t\n\r'.includes(text[b])) b--; + const prev = text[b]; + if ((c === '}' || c === ']') && prev === ',') return `There's an extra comma before this ${c}. JSON doesn't allow a comma after the last item.`; + if (c === "'") return 'JSON needs double quotes ("like this"), not single quotes.'; + if (/[A-Za-z_$]/.test(c || '') && (prev === '{' || prev === ',')) return 'Keys need double quotes in JSON, like "name": …'; + if ((c === '"' || c === '{' || c === '[') && (prev === '"' || prev === '}' || prev === ']' || /[\deE]/.test(prev || ''))) return 'A comma is missing before this value.'; + if (c === undefined) return 'The JSON ends too early: something isn’t closed.'; + return ''; + } + + const kindOf = v => v === null ? 'null' : v instanceof Num ? 'number' : Array.isArray(v) ? 'array' : typeof v; + + /** A JavaScript-style path to a value: $.users[2].email, or $["odd key"] for keys that aren't identifiers. */ + function pathOf(parts) { + let out = '$'; + for (const p of parts) { + if (typeof p === 'number') out += `[${p}]`; + else if (/^[A-Za-z_$][\w$]*$/.test(p)) out += '.' + p; + else out += `[${JSON.stringify(p)}]`; + } + return out; + } + + /** JSON text for a value, keeping Num exactly as written. indent: 0 for one line, a number of spaces, or '\t'. */ + function stringify(value, indent) { + const unit = indent === '\t' ? '\t' : ' '.repeat(Math.max(0, +indent || 0)); + const nl = unit ? '\n' : ''; + const sep = unit ? ': ' : ':'; + function go(v, pad) { + if (v instanceof Num) return v.source; + if (v === null || typeof v !== 'object') return JSON.stringify(v) ?? 'null'; + const inner = pad + unit; + if (Array.isArray(v)) { + if (!v.length) return '[]'; + return '[' + nl + v.map(x => inner + go(x, inner)).join(',' + nl) + nl + pad + ']'; + } + const keys = Object.keys(v); + if (!keys.length) return '{}'; + return '{' + nl + keys.map(k => inner + JSON.stringify(k) + sep + go(v[k], inner)).join(',' + nl) + nl + pad + '}'; + } + return go(value, ''); + } + + /** A short description of a value: "3 keys", "120 items", or the value itself. */ + function describe(v) { + const k = kindOf(v); + if (k === 'array') return v.length === 1 ? '1 item' : `${v.length} items`; + if (k === 'object') { const n = Object.keys(v).length; return n === 1 ? '1 key' : `${n} keys`; } + return k; + } + + /** + * Finds keys and values containing the query (case-insensitive). Returns the paths (as arrays) of the matches, + * in document order, at most `limit` of them. + */ + function search(value, query, limit = 2000) { + const q = String(query || '').trim().toLowerCase(); + const hits = []; + if (!q) return hits; + (function walk(v, parts) { + if (hits.length >= limit) return; + if (v !== null && typeof v === 'object' && !(v instanceof Num)) { + const entries = Array.isArray(v) ? v.map((x, i) => [i, x]) : Object.entries(v); + for (const [k, x] of entries) { + if (hits.length >= limit) return; + const here = parts.concat([k]); + const leaf = x === null || typeof x !== 'object' || x instanceof Num; + if ((typeof k === 'string' && k.toLowerCase().includes(q)) || (leaf && String(x).toLowerCase().includes(q))) hits.push(here); + if (!leaf) walk(x, here); + } + } + })(value, []); + return hits; + } + + /** How many values there are in all, to decide how much to open at first. Stops counting at `cap`. */ + function countNodes(value, cap = 100000) { + let n = 0; + (function walk(v) { + if (n >= cap) return; + n++; + if (v !== null && typeof v === 'object' && !(v instanceof Num)) for (const x of Array.isArray(v) ? v : Object.values(v)) { if (n >= cap) return; walk(x); } + })(value); + return n; + } + + const isLink = s => typeof s === 'string' && s.length < 2048 && /^https?:\/\/[^\s"<>]+$/i.test(s); + + /** Splits pretty JSON into tokens for colouring: [type, text] with type key, string, number, boolean, null, punct or space. */ + function tokenize(text) { + const out = []; + const re = /("(?:[^"\\]|\\.)*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false)\b|\b(null)\b|([{}\[\],:])|(\s+)|([^\s])/g; + let m; + while ((m = re.exec(text))) { + if (m[1]) { out.push([m[2] ? 'key' : 'string', m[1]]); if (m[2]) out.push(['punct', m[2]]); } + else if (m[3]) out.push(['number', m[3]]); + else if (m[4]) out.push(['boolean', m[4]]); + else if (m[5]) out.push(['null', m[5]]); + else if (m[6]) out.push(['punct', m[6]]); + else if (m[7]) out.push(['space', m[7]]); + else out.push(['punct', m[8]]); + } + return out; + } + + return { Num, isJsonType, looksLikeJson, stripPrefix, errorOffset, lineColumn, parse, kindOf, pathOf, stringify, describe, search, countNodes, isLink, tokenize }; +}); diff --git a/browser/json-viewer/src/render.js b/browser/json-viewer/src/render.js new file mode 100644 index 0000000..45e69f0 --- /dev/null +++ b/browser/json-viewer/src/render.js @@ -0,0 +1,351 @@ +/* + * JSON Viewer Veyra: the viewer. VJV.mount(host, options) draws the toolbar, the tree, the raw view and the path bar. + * Every value from the page is put in with textContent, never as HTML, so a JSON document can't run anything. + */ +(function (root) { + 'use strict'; + const V = root.VJV; + const CHUNK = 200; // array items and object keys shown at a time + + function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text !== undefined) e.textContent = text; + return e; + } + function button(label, title, onClick, cls) { + const b = el('button', 'vjv-btn' + (cls ? ' ' + cls : ''), label); + b.type = 'button'; b.title = title; b.setAttribute('aria-label', title); + b.addEventListener('click', onClick); + return b; + } + const keyOf = parts => JSON.stringify(parts); + const isContainer = v => v !== null && typeof v === 'object' && !(v instanceof V.Num); + + async function copyText(text) { + try { await navigator.clipboard.writeText(text); return true; } catch { /* fall back below */ } + const t = el('textarea'); t.value = text; t.style.cssText = 'position:fixed;left:-9999px;top:0'; + document.body.appendChild(t); t.select(); + let ok = false; try { ok = document.execCommand('copy'); } catch { ok = false; } + t.remove(); return ok; + } + + /** + * Mounts the viewer into host. + * options: { text, parsed, settings: {theme, indent, view}, saveSettings(s), title, original } + */ + function mount(host, options) { + const settings = Object.assign({ theme: 'auto', indent: 2, view: 'tree' }, options.settings || {}); + const parsed = options.parsed || V.parse(options.text); + const value = parsed.ok ? parsed.value : undefined; + const save = () => { try { options.saveSettings && options.saveSettings(settings); } catch { /* settings are a nicety */ } }; + let view = 'tree'; // which pane is showing: tree, raw or original + let rawDirty = true; // the raw pane needs redrawing (new indent) + + const rootEl = el('div', 'vjv'); + rootEl.dataset.theme = settings.theme; + host.appendChild(rootEl); + + // ---- toolbar + const bar = el('div', 'vjv-bar'); + const brand = el('span', 'vjv-brand', '{ } JSON Viewer'); + const tabs = el('div', 'vjv-tabs'); tabs.setAttribute('role', 'tablist'); + const tabTree = button('Tree', 'Show as a tree', () => show('tree'), 'vjv-tab'); + const tabRaw = button('Raw', 'Show formatted JSON', () => show('raw'), 'vjv-tab'); + const tabOrig = button('Original', 'Show the text as the page sent it', () => show('original'), 'vjv-tab'); + for (const t of [tabTree, tabRaw, tabOrig]) t.setAttribute('role', 'tab'); + tabs.append(tabTree, tabRaw, tabOrig); + const searchBox = el('input', 'vjv-search'); + searchBox.type = 'search'; searchBox.placeholder = 'Search keys and values'; searchBox.setAttribute('aria-label', 'Search keys and values'); + const hitsLabel = el('span', 'vjv-hits'); + const prev = button('↑', 'Previous match (Shift+Enter)', () => step(-1)); + const next = button('↓', 'Next match (Enter)', () => step(1)); + const expandAll = button('Expand all', 'Open every level', () => openAll(true)); + const collapseAll = button('Collapse all', 'Close every level', () => openAll(false)); + const indentSel = el('select', 'vjv-select'); indentSel.title = 'Indentation for Raw, Copy and Download'; indentSel.setAttribute('aria-label', 'Indentation'); + for (const [v, l] of [['2', '2 spaces'], ['4', '4 spaces'], ['\t', 'Tabs'], ['0', 'One line']]) { const o = el('option', '', l); o.value = v; indentSel.appendChild(o); } + indentSel.value = String(settings.indent); + indentSel.addEventListener('change', () => { settings.indent = indentSel.value === '\t' ? '\t' : +indentSel.value; save(); rawDirty = true; if (view === 'raw') renderRaw(); }); + const copyAll = button('Copy', 'Copy the JSON', async () => flash(copyAll, await copyText(formatted()) ? 'Copied' : 'Copy failed')); + const download = button('Download', 'Save as a .json file', () => { + const url = URL.createObjectURL(new Blob([formatted()], { type: 'application/json' })); + const a = el('a'); a.href = url; a.download = (options.title || 'data').replace(/[^\w.-]+/g, '_').replace(/(\.json)?$/i, '.json'); + document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); + }); + const themes = ['auto', 'dark', 'light']; + const themeBtn = button('', 'Theme', () => { settings.theme = themes[(themes.indexOf(settings.theme) + 1) % 3]; rootEl.dataset.theme = settings.theme; themeBtn.textContent = themeLabel(); save(); }); + const themeLabel = () => settings.theme === 'auto' ? '◐ Auto' : settings.theme === 'dark' ? '● Dark' : '○ Light'; + themeBtn.textContent = themeLabel(); + const searchWrap = el('div', 'vjv-searchwrap'); searchWrap.append(searchBox, hitsLabel, prev, next); + const tools = el('div', 'vjv-tools'); tools.append(expandAll, collapseAll, indentSel, copyAll, download, themeBtn); + bar.append(brand, tabs, searchWrap, tools); + rootEl.appendChild(bar); + + // ---- path bar + const pathBar = el('div', 'vjv-pathbar'); + const pathText = el('code', 'vjv-path', '$'); + const copyPath = button('Copy path', 'Copy the path of the selected value', async () => flash(copyPath, await copyText(pathText.textContent) ? 'Copied' : 'Copy failed')); + const copyValue = button('Copy value', 'Copy the selected value', async () => flash(copyValue, await copyText(selectedValueText()) ? 'Copied' : 'Copy failed')); + const summary = el('span', 'vjv-summary'); + pathBar.append(pathText, summary, copyPath, copyValue); + rootEl.appendChild(pathBar); + + const body = el('div', 'vjv-body'); + rootEl.appendChild(body); + const treePane = el('div', 'vjv-tree'); treePane.setAttribute('role', 'tree'); treePane.tabIndex = 0; + const rawPane = el('pre', 'vjv-raw'); + const origPane = el('pre', 'vjv-raw vjv-original'); + body.append(treePane, rawPane, origPane); + + function flash(btn, text) { const old = btn.textContent; btn.textContent = text; btn.disabled = true; setTimeout(() => { btn.textContent = old; btn.disabled = false; }, 1200); } + const formatted = () => parsed.ok ? V.stringify(value, settings.indent) : options.text; + + // ---- error: say where, and show the text with that line marked + if (!parsed.ok) { + const err = el('div', 'vjv-error'); + err.appendChild(el('b', '', 'This JSON has a mistake')); + err.appendChild(el('span', '', parsed.where ? ` on line ${parsed.where.line}, column ${parsed.where.column}: ${parsed.error}` : `: ${parsed.error}`)); + rootEl.insertBefore(err, body); + for (const b of [tabTree, tabRaw, expandAll, collapseAll, searchWrap, copyValue, copyPath, indentSel]) b.style.display = 'none'; + pathBar.style.display = 'none'; + const lines = options.text.split('\n'); + lines.forEach((line, i) => { + const row = el('div', 'vjv-line' + (parsed.where && parsed.where.line === i + 1 ? ' vjv-line-bad' : '')); + row.appendChild(el('span', 'vjv-ln', String(i + 1))); + row.appendChild(el('span', '', line || ' ')); + origPane.appendChild(row); + }); + show('original'); + const bad = origPane.querySelector('.vjv-line-bad'); + if (bad) setTimeout(() => bad.scrollIntoView({ block: 'center' }), 0); + return { root: rootEl }; + } + origPane.textContent = options.original ?? options.text; + + // ---- the tree, drawn lazily: a container's children are made the first time it opens + const nodes = new Map(); // keyOf(parts) -> record + const recOf = new WeakMap(); // a node's wrap or row element -> record + let selected = null; + const total = V.countNodes(value, 20000); + + function makeNode(key, v, parts, depth) { + const rec = { parts, v, depth, open: false, built: false, shown: 0 }; + const wrap = el('div', 'vjv-node'); + const row = el('div', 'vjv-row'); row.setAttribute('role', 'treeitem'); row.tabIndex = -1; + row.style.setProperty('--d', depth); + rec.row = row; rec.wrap = wrap; + const container = isContainer(v); + const empty = container && (Array.isArray(v) ? !v.length : !Object.keys(v).length); + const tog = el('span', 'vjv-tog' + (container && !empty ? '' : ' vjv-tog-none'), container && !empty ? '▸' : ''); + tog.setAttribute('aria-hidden', 'true'); + row.appendChild(tog); + if (key !== null) { + row.appendChild(el('span', typeof key === 'number' ? 'vjv-idx' : 'vjv-key', typeof key === 'number' ? String(key) : JSON.stringify(key))); + row.appendChild(el('span', 'vjv-colon', ':')); + } + if (container) { + const arr = Array.isArray(v); + row.appendChild(el('span', 'vjv-brace', arr ? '[' : '{')); + rec.more = el('span', 'vjv-more', empty ? '' : V.describe(v)); + row.appendChild(rec.more); + rec.close = el('span', 'vjv-brace vjv-close', arr ? ']' : '}'); + row.appendChild(rec.close); + if (!empty) { + row.setAttribute('aria-expanded', 'false'); + rec.kids = el('div', 'vjv-kids'); rec.kids.setAttribute('role', 'group'); rec.kids.hidden = true; + rec.end = el('div', 'vjv-row vjv-endrow'); rec.end.style.setProperty('--d', depth); + rec.end.append(el('span', 'vjv-tog vjv-tog-none'), el('span', 'vjv-brace', arr ? ']' : '}')); + rec.end.hidden = true; + tog.addEventListener('click', e => { e.stopPropagation(); toggle(rec); }); + row.addEventListener('dblclick', e => { e.preventDefault(); toggle(rec); }); + } + } else { + row.appendChild(leaf(v)); + } + row.addEventListener('click', () => select(rec)); + wrap.appendChild(row); + if (rec.kids) wrap.append(rec.kids, rec.end); + nodes.set(keyOf(parts), rec); + recOf.set(wrap, rec); recOf.set(row, rec); + return rec; + } + /** The child records of an open container, in order. */ + const childrenOf = rec => rec.kids ? [...rec.kids.children].map(c => recOf.get(c)).filter(Boolean) : []; + + function leaf(v) { + const kind = V.kindOf(v); + if (kind === 'string') { + const s = el('span', 'vjv-str'); + const full = JSON.stringify(v); + if (V.isLink(v)) { + s.appendChild(document.createTextNode('"')); + const a = el('a', 'vjv-link', v); a.href = v; a.target = '_blank'; a.rel = 'noopener noreferrer nofollow'; + a.addEventListener('click', e => e.stopPropagation()); + s.appendChild(a); s.appendChild(document.createTextNode('"')); + } else if (full.length > 400) { + const short = el('span', '', full.slice(0, 300) + '…'); + const more = el('button', 'vjv-showall', `show all ${v.length.toLocaleString('en')} characters`); more.type = 'button'; + more.addEventListener('click', e => { e.stopPropagation(); short.textContent = full; more.remove(); }); + s.append(short, more); + } else s.textContent = full; + return s; + } + return el('span', 'vjv-' + kind, kind === 'number' ? String(v) : JSON.stringify(v)); + } + + /** Adds the next CHUNK of a container's children, with a "show more" row if there are still more. */ + function build(rec, upTo) { + const v = rec.v; + const entries = Array.isArray(v) ? v : Object.keys(v); + const count = entries.length; + const until = Math.min(count, Math.max(rec.shown + CHUNK, upTo == null ? 0 : upTo + 1)); + if (rec.moreBtn) { rec.moreBtn.remove(); rec.moreBtn = null; } + const frag = document.createDocumentFragment(); + for (let i = rec.shown; i < until; i++) { + const k = Array.isArray(v) ? i : entries[i]; + frag.appendChild(makeNode(k, v[k], rec.parts.concat([k]), rec.depth + 1).wrap); + } + rec.kids.appendChild(frag); + rec.shown = until; rec.built = true; + if (until < count) { + const left = count - until; + rec.moreBtn = el('div', 'vjv-row vjv-morerow'); rec.moreBtn.style.setProperty('--d', rec.depth + 1); + const b = el('button', 'vjv-showall', `Show ${Math.min(CHUNK, left).toLocaleString('en')} more of ${left.toLocaleString('en')}`); b.type = 'button'; + b.addEventListener('click', e => { e.stopPropagation(); build(rec); }); + rec.moreBtn.appendChild(b); + rec.kids.appendChild(rec.moreBtn); + } + } + + function setOpen(rec, open) { + if (!rec.kids || rec.open === open) return; + if (open && !rec.built) build(rec); + rec.open = open; + rec.kids.hidden = !open; rec.end.hidden = !open; + rec.more.hidden = open; rec.close.hidden = open; + rec.row.setAttribute('aria-expanded', String(open)); + rec.row.firstChild.textContent = open ? '▾' : '▸'; + } + const toggle = rec => setOpen(rec, !rec.open); + + function select(rec) { + if (selected) { selected.row.classList.remove('vjv-sel'); selected.row.tabIndex = -1; } + selected = rec; + rec.row.classList.add('vjv-sel'); rec.row.tabIndex = 0; + pathText.textContent = V.pathOf(rec.parts); + summary.textContent = V.describe(rec.v); + } + const selectedValueText = () => selected ? (isContainer(selected.v) ? V.stringify(selected.v, settings.indent) : V.kindOf(selected.v) === 'string' ? selected.v : String(selected.v)) : formatted(); + + /** Opens every container on the way to a path, building chunks as needed, and returns the record there. */ + function reveal(parts) { + let rec = nodes.get(keyOf([])); + for (let i = 0; i < parts.length; i++) { + if (!rec.built || (typeof parts[i] === 'number' && parts[i] >= rec.shown) || (typeof parts[i] === 'string' && !nodes.has(keyOf(parts.slice(0, i + 1))))) { + const idx = typeof parts[i] === 'number' ? parts[i] : Object.keys(rec.v).indexOf(parts[i]); + build(rec, idx); + } + setOpen(rec, true); + rec = nodes.get(keyOf(parts.slice(0, i + 1))); + if (!rec) return null; + } + return rec; + } + + function openAll(open) { + if (open && total > 20000 && !confirm('This JSON is very large. Opening everything may take a while. Continue?')) return; + (function walk(rec) { + if (!rec.kids) return; + if (open) { if (!rec.built) build(rec); while (rec.shown < (Array.isArray(rec.v) ? rec.v.length : Object.keys(rec.v).length) && rec.shown < 5000) build(rec); } + setOpen(rec, open); + for (const r of childrenOf(rec)) walk(r); + })(rootRec); + if (!open) setOpen(rootRec, true); + } + + const rootRec = makeNode(null, value, [], 0); + treePane.appendChild(rootRec.wrap); + + // open the first levels: everything when it's small, otherwise the top level and small children + if (isContainer(value)) { + setOpen(rootRec, true); + const deep = total <= 300 ? 6 : 1; + (function open(rec, d) { + if (d >= deep) return; + for (const r of childrenOf(rec)) { + // the top level always opens (only the first 200 children are drawn); deeper, only small containers + if (r.kids && (d === 0 || (Array.isArray(r.v) ? r.v.length : Object.keys(r.v).length) <= 50)) { setOpen(r, true); open(r, d + 1); } + } + })(rootRec, 0); + } + select(rootRec); + + // keyboard: up/down move, right/left open/close, Enter toggles + treePane.addEventListener('keydown', e => { + if (!selected) return; + const rows = [...treePane.querySelectorAll('.vjv-row[role="treeitem"]')].filter(r => r.offsetParent !== null); + const i = rows.indexOf(selected.row); + const go = r => { const rec = recOf.get(r); if (rec) { select(rec); r.focus(); r.scrollIntoView({ block: 'nearest' }); } }; + if (e.key === 'ArrowDown' && i < rows.length - 1) { go(rows[i + 1]); e.preventDefault(); } + else if (e.key === 'ArrowUp' && i > 0) { go(rows[i - 1]); e.preventDefault(); } + else if (e.key === 'ArrowRight' && selected.kids) { setOpen(selected, true); e.preventDefault(); } + else if (e.key === 'ArrowLeft') { if (selected.open) setOpen(selected, false); else if (selected.parts.length) go(nodes.get(keyOf(selected.parts.slice(0, -1))).row); e.preventDefault(); } + else if (e.key === 'Enter' && selected.kids) { toggle(selected); e.preventDefault(); } + }); + + // ---- search + let hits = [], at = -1, timer; + function clearHits() { for (const r of treePane.querySelectorAll('.vjv-hit,.vjv-hit-now')) r.classList.remove('vjv-hit', 'vjv-hit-now'); } + function runSearch() { + clearHits(); + hits = V.search(value, searchBox.value, 2000); at = -1; + if (!searchBox.value.trim()) { hitsLabel.textContent = ''; return; } + if (!hits.length) { hitsLabel.textContent = 'No matches'; return; } + if (view !== 'tree') show('tree'); + for (const p of hits.slice(0, 300)) { const r = reveal(p); if (r) r.row.classList.add('vjv-hit'); } + step(1); + } + function step(dir) { + if (!hits.length) return; + at = (at + dir + hits.length) % hits.length; + treePane.querySelector('.vjv-hit-now')?.classList.remove('vjv-hit-now'); + const rec = reveal(hits[at]); + if (rec) { rec.row.classList.add('vjv-hit', 'vjv-hit-now'); select(rec); rec.row.scrollIntoView({ block: 'center' }); } + hitsLabel.textContent = `${at + 1} of ${hits.length}${hits.length >= 2000 ? '+' : ''}`; + } + searchBox.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(runSearch, 220); }); + searchBox.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); step(e.shiftKey ? -1 : 1); } if (e.key === 'Escape') { searchBox.value = ''; runSearch(); } }); + document.addEventListener('keydown', e => { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f' && view !== 'original') { e.preventDefault(); searchBox.focus(); searchBox.select(); } + }); + + // ---- raw view, coloured (plain above 3 MB, to stay fast) + function renderRaw() { + if (!rawDirty) return; + rawDirty = false; + const text = V.stringify(value, settings.indent === 0 ? 2 : settings.indent); + rawPane.textContent = ''; + if (text.length > 3e6) { rawPane.textContent = text; return; } + const frag = document.createDocumentFragment(); + for (const [type, t] of V.tokenize(text)) { + if (type === 'space' || type === 'punct') frag.appendChild(document.createTextNode(t)); + else frag.appendChild(el('span', 'vjv-t-' + type, t)); + } + rawPane.appendChild(frag); + } + + function show(which) { + view = which; + treePane.hidden = which !== 'tree'; rawPane.hidden = which !== 'raw'; origPane.hidden = which !== 'original'; + for (const [t, w] of [[tabTree, 'tree'], [tabRaw, 'raw'], [tabOrig, 'original']]) { t.classList.toggle('vjv-on', w === which); t.setAttribute('aria-selected', String(w === which)); } + expandAll.disabled = collapseAll.disabled = which !== 'tree'; + if (which === 'raw') renderRaw(); + if (parsed.ok && settings.view !== which && which !== 'original') { settings.view = which; save(); } + } + show(settings.view === 'raw' ? 'raw' : 'tree'); + + return { root: rootEl, reveal, select, nodes, search: q => { searchBox.value = q; runSearch(); }, show }; + } + + root.VJV = Object.assign(root.VJV || {}, { mount }); +})(typeof self !== 'undefined' ? self : this); diff --git a/browser/json-viewer/src/viewer.css b/browser/json-viewer/src/viewer.css new file mode 100644 index 0000000..f2f46d4 --- /dev/null +++ b/browser/json-viewer/src/viewer.css @@ -0,0 +1,107 @@ +/* + * JSON Viewer Veyra. Chrome adds this file to every page, so every rule is scoped to the viewer (.vjv, .vjv-page, + * .vjv-app) and does nothing anywhere else. + */ +.vjv, .vjv-app { + --bg: #0f1218; --panel: #151a22; --line: #252c38; --text: #d7dde6; --muted: #7d8a99; --accent: #4fd1b5; + --key: #8cc8ff; --str: #a8e08a; --num: #ffb86b; --bool: #d4a5ff; --null: #ff8fa3; --sel: #1d3a5a; --hit: #4a3d12; --hitnow: #7a5d0a; + --btn: #1c222c; --btnh: #252d3a; --err: #3a1820; --errline: #5a1f2c; +} +.vjv[data-theme="light"] { + --bg: #ffffff; --panel: #f6f8fa; --line: #e3e7ec; --text: #1f2933; --muted: #6b7785; --accent: #0f8f75; + --key: #0a58b8; --str: #2f7d1e; --num: #b5530a; --bool: #7a3ec2; --null: #c2264a; --sel: #dcebff; --hit: #fff1b8; --hitnow: #ffd75e; + --btn: #eef1f4; --btnh: #e2e7ec; --err: #ffe8ec; --errline: #ffd0d9; +} +@media (prefers-color-scheme: light) { + .vjv[data-theme="auto"], .vjv-app { + --bg: #ffffff; --panel: #f6f8fa; --line: #e3e7ec; --text: #1f2933; --muted: #6b7785; --accent: #0f8f75; + --key: #0a58b8; --str: #2f7d1e; --num: #b5530a; --bool: #7a3ec2; --null: #c2264a; --sel: #dcebff; --hit: #fff1b8; --hitnow: #ffd75e; + --btn: #eef1f4; --btnh: #e2e7ec; --err: #ffe8ec; --errline: #ffd0d9; + } +} + +html.vjv-page, html.vjv-page body { margin: 0; padding: 0; height: 100%; } +html.vjv-page body { background: #0f1218; } +@media (prefers-color-scheme: light) { html.vjv-page body { background: #fff; } } + +.vjv { position: fixed; inset: 0; display: flex; flex-direction: column; background: var(--bg); color: var(--text); font: 13px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color-scheme: dark; } +.vjv[data-theme="light"] { color-scheme: light; } +.vjv *, .vjv *::before, .vjv *::after { box-sizing: border-box; } +.vjv [hidden] { display: none !important; } + +/* toolbar */ +.vjv-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 8px 12px; background: var(--panel); border-bottom: 1px solid var(--line); } +.vjv-brand { font: 700 13px ui-monospace, "Cascadia Code", Consolas, monospace; color: var(--accent); white-space: nowrap; } +.vjv-tabs { display: flex; background: var(--btn); border-radius: 8px; padding: 2px; } +.vjv-btn { font: 500 12px system-ui, sans-serif; color: var(--text); background: var(--btn); border: 1px solid var(--line); border-radius: 7px; padding: 5px 10px; cursor: pointer; white-space: nowrap; } +.vjv-btn:hover { background: var(--btnh); } +.vjv-btn:disabled { opacity: .45; cursor: default; } +.vjv-btn:focus-visible, .vjv-search:focus-visible, .vjv-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.vjv-tab { border: 0; background: transparent; padding: 4px 12px; border-radius: 6px; } +.vjv-tab.vjv-on { background: var(--bg); color: var(--accent); box-shadow: 0 1px 2px #0003; } +.vjv-searchwrap { display: flex; align-items: center; gap: 4px; flex: 1 1 260px; min-width: 0; } +.vjv-search { flex: 1; min-width: 0; font: 13px system-ui, sans-serif; color: var(--text); background: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 5px 10px; } +.vjv-hits { color: var(--muted); font-size: 12px; white-space: nowrap; min-width: 0; } +.vjv-tools { display: flex; gap: 6px; flex-wrap: wrap; } +.vjv-select { font: 12px system-ui, sans-serif; color: var(--text); background: var(--btn); border: 1px solid var(--line); border-radius: 7px; padding: 4px 6px; } +.vjv-back { margin-right: 2px; } + +/* path bar */ +.vjv-pathbar { display: flex; align-items: center; gap: 10px; padding: 5px 12px; border-bottom: 1px solid var(--line); background: var(--bg); min-height: 34px; } +.vjv-path { font: 12.5px ui-monospace, "Cascadia Code", Consolas, monospace; color: var(--accent); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 0 1 auto; } +.vjv-summary { color: var(--muted); font-size: 12px; margin-right: auto; white-space: nowrap; } +.vjv-pathbar .vjv-btn { padding: 3px 8px; font-size: 11.5px; } + +/* the tree */ +.vjv-body { flex: 1; overflow: auto; } +.vjv-tree, .vjv-raw { font: 13px/1.6 ui-monospace, "Cascadia Code", "SF Mono", Consolas, monospace; } +.vjv-tree { padding: 8px 0 40px; outline: none; } +.vjv-row { display: flex; align-items: baseline; padding: 0 12px 0 calc(12px + var(--d, 0) * 18px); white-space: nowrap; cursor: default; border-radius: 0; } +.vjv-row:hover { background: color-mix(in srgb, var(--sel) 45%, transparent); } +.vjv-row.vjv-sel { background: var(--sel); } +.vjv-row.vjv-hit { background: var(--hit); } +.vjv-row.vjv-hit-now { background: var(--hitnow); } +.vjv-row:focus { outline: none; } +.vjv-tog { display: inline-block; width: 16px; flex: none; color: var(--muted); cursor: pointer; user-select: none; text-align: center; } +.vjv-tog-none { cursor: default; } +.vjv-key { color: var(--key); } +.vjv-idx { color: var(--muted); } +.vjv-colon, .vjv-brace { color: var(--muted); } +.vjv-colon { margin-right: .6ch; } +.vjv-more { color: var(--muted); font: italic 12px system-ui, sans-serif; margin: 0 6px; } +.vjv-str { color: var(--str); white-space: pre-wrap; word-break: break-word; } +.vjv-number { color: var(--num); } +.vjv-boolean { color: var(--bool); } +.vjv-null { color: var(--null); } +.vjv-link { color: var(--str); text-decoration: underline; text-decoration-color: color-mix(in srgb, var(--str) 50%, transparent); } +.vjv-link:hover { text-decoration-color: currentColor; } +.vjv-showall { font: 12px system-ui, sans-serif; color: var(--accent); background: none; border: 0; padding: 0 6px; cursor: pointer; text-decoration: underline; } +.vjv-morerow { padding-top: 2px; padding-bottom: 2px; } + +/* raw and original */ +.vjv-raw { margin: 0; padding: 12px 16px 40px; white-space: pre-wrap; word-break: break-word; color: var(--text); } +.vjv-t-key { color: var(--key); } .vjv-t-string { color: var(--str); } .vjv-t-number { color: var(--num); } .vjv-t-boolean { color: var(--bool); } .vjv-t-null { color: var(--null); } +.vjv-line { display: flex; } +.vjv-ln { flex: none; width: 52px; padding-right: 14px; text-align: right; color: var(--muted); user-select: none; } +.vjv-line-bad { background: var(--errline); } +.vjv-error { padding: 10px 14px; background: var(--err); border-bottom: 1px solid var(--line); } +.vjv-error b { color: var(--null); } + +@media (max-width: 640px) { + .vjv-brand { display: none; } + .vjv-tools .vjv-btn { padding: 5px 8px; } +} + +/* the start page behind the toolbar button */ +.vjv-app { margin: 0; min-height: 100vh; background: var(--bg); color: var(--text); font: 14px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +.vjv-start { max-width: 760px; margin: 0 auto; padding: 48px 20px; } +.vjv-start h1 { margin: 0 0 6px; font-size: 26px; letter-spacing: -.4px; } +.vjv-start h1 span { color: var(--accent); font-family: ui-monospace, Consolas, monospace; } +.vjv-start p { margin: 0 0 18px; color: var(--muted); } +.vjv-start textarea { width: 100%; min-height: 320px; box-sizing: border-box; padding: 14px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); color: var(--text); font: 13px/1.55 ui-monospace, "Cascadia Code", Consolas, monospace; resize: vertical; } +.vjv-start textarea:focus { outline: 2px solid var(--accent); outline-offset: 1px; } +.vjv-start-actions { display: flex; flex-wrap: wrap; gap: 10px; margin: 14px 0 22px; } +.vjv-start-actions button, .vjv-file { font: 600 13px system-ui, sans-serif; color: var(--text); background: var(--btn); border: 1px solid var(--line); border-radius: 9px; padding: 9px 16px; cursor: pointer; } +.vjv-start-actions .vjv-primary { background: var(--accent); border-color: var(--accent); color: #062019; } +.vjv-file input { display: none; } +.vjv-tip { font-size: 12.5px; } diff --git a/browser/json-viewer/src/viewer.html b/browser/json-viewer/src/viewer.html new file mode 100644 index 0000000..da15bfd --- /dev/null +++ b/browser/json-viewer/src/viewer.html @@ -0,0 +1,27 @@ + + + + + + JSON Viewer + + + + +
+

{ } JSON Viewer

+

Paste JSON, drop a file, or open one. It stays on your computer.

+ +
+ + + +
+

JSON pages you open in Chrome are shown as a tree automatically.

+
+
+ + + + + diff --git a/browser/json-viewer/src/viewer.js b/browser/json-viewer/src/viewer.js new file mode 100644 index 0000000..6ca1847 --- /dev/null +++ b/browser/json-viewer/src/viewer.js @@ -0,0 +1,49 @@ +// JSON Viewer Veyra: the page behind the toolbar button. Paste JSON, drop a file or open one, and view it. +(function () { + 'use strict'; + const V = window.VJV; + const $ = id => document.getElementById(id); + const KEY = 'vjvSettings'; + const storage = typeof chrome !== 'undefined' && chrome.storage && chrome.storage.sync; + // An example with a big number and a price written as 19.90: both are shown exactly as written. + const SAMPLE = [ + '{', + ' "store": "Neon Books",', + ' "open": true,', + ' "rating": 4.8,', + ' "orderId": 9007199254740993123,', + ' "price": 19.90,', + ' "tags": ["books", "coffee"],', + ' "owner": { "name": "Ada", "site": "https://example.com" },', + ' "hours": [', + ' { "day": "Mon", "from": "09:00", "to": "18:00" },', + ' { "day": "Sat", "from": "10:00", "to": "16:00" }', + ' ],', + ' "closedOn": null', + '}', + ].join('\n'); + + async function show(text, title) { + let settings; + try { settings = storage ? (await storage.get(KEY))[KEY] : undefined; } catch { settings = undefined; } + $('start').hidden = true; + document.documentElement.classList.add('vjv-page'); + const out = $('out'); out.textContent = ''; + const back = document.createElement('button'); back.type = 'button'; back.className = 'vjv-back'; back.textContent = '← New'; + back.addEventListener('click', () => { out.textContent = ''; $('start').hidden = false; document.documentElement.classList.remove('vjv-page'); $('input').focus(); }); + V.mount(out, { text, settings, title: title || 'data', saveSettings: s => storage && storage.set({ [KEY]: s }) }); + out.querySelector('.vjv-bar')?.prepend(back); + } + const readFile = file => file && file.text().then(t => show(t, file.name.replace(/\.[^.]+$/, ''))); + + $('view').addEventListener('click', () => { const t = $('input').value; if (t.trim()) show(t); else $('input').focus(); }); + $('sample').addEventListener('click', () => { $('input').value = SAMPLE; show(SAMPLE, 'example'); }); + $('file').addEventListener('change', e => readFile(e.target.files[0])); + $('input').addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) $('view').click(); }); + document.addEventListener('dragover', e => e.preventDefault()); + document.addEventListener('drop', e => { e.preventDefault(); readFile(e.dataTransfer.files[0]); }); + document.addEventListener('paste', e => { + if (!$('start').hidden && document.activeElement !== $('input')) { const t = e.clipboardData.getData('text'); if (t.trim()) { $('input').value = t; show(t); } } + }); + $('input').focus(); +})(); diff --git a/browser/json-viewer/store/1-tree.png b/browser/json-viewer/store/1-tree.png new file mode 100644 index 0000000..05bdfa6 Binary files /dev/null and b/browser/json-viewer/store/1-tree.png differ diff --git a/browser/json-viewer/store/2-search.png b/browser/json-viewer/store/2-search.png new file mode 100644 index 0000000..87e480f Binary files /dev/null and b/browser/json-viewer/store/2-search.png differ diff --git a/browser/json-viewer/store/3-raw.png b/browser/json-viewer/store/3-raw.png new file mode 100644 index 0000000..5595e0f Binary files /dev/null and b/browser/json-viewer/store/3-raw.png differ diff --git a/browser/json-viewer/store/4-error.png b/browser/json-viewer/store/4-error.png new file mode 100644 index 0000000..5f95204 Binary files /dev/null and b/browser/json-viewer/store/4-error.png differ diff --git a/browser/json-viewer/store/5-light.png b/browser/json-viewer/store/5-light.png new file mode 100644 index 0000000..86801fb Binary files /dev/null and b/browser/json-viewer/store/5-light.png differ diff --git a/browser/json-viewer/store/promo-440x280.png b/browser/json-viewer/store/promo-440x280.png new file mode 100644 index 0000000..e0dc027 Binary files /dev/null and b/browser/json-viewer/store/promo-440x280.png differ diff --git a/browser/json-viewer/test/browser.test.mjs b/browser/json-viewer/test/browser.test.mjs new file mode 100644 index 0000000..7e4f862 --- /dev/null +++ b/browser/json-viewer/test/browser.test.mjs @@ -0,0 +1,161 @@ +// Loads the extension into Chromium with Playwright and checks it on real pages from a local server. +// Run: node test/browser.test.mjs (PLAYWRIGHT_PATH can point at a playwright package; default: the repo's) +import http from "node:http"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const ext = path.resolve(here, ".."); +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_PATH || path.resolve(ext, "../../node_modules/playwright")); + +const data = { + user: { name: "Ada Lovelace", email: "ada@example.com", site: "https://example.com/ada" }, + orderId: "__BIG__", + price: "__PRICE__", + items: [{ sku: "A-1", qty: 2 }, { sku: "B-7", qty: 1 }], + active: true, + note: null, +}; +const dataText = JSON.stringify(data, null, 2).replace('"__BIG__"', "12345678901234567890").replace('"__PRICE__"', "19.90"); +const pages = { + "/data.json": ["application/json; charset=utf-8", dataText], + "/plain.txt": ["text/plain", '{"plain": [1, 2, 3]}'], + "/notjson.txt": ["text/plain", "just some {text}"], + "/broken.json": ["application/json", '{\n "a": 1,\n "b": 2,\n}'], + "/xssi.json": ["application/json", ")]}'\n{\"safe\": true}"], + "/evil.json": ["application/json", JSON.stringify({ html: "", js: "javascript:window.__pwned=2" })], + "/page.html": ["text/html", "t
{\"a\": 1}
"], + "/big.json": ["application/json", JSON.stringify({ rows: Array.from({ length: 5000 }, (_, i) => ({ id: i, name: "row " + i })) })], +}; +const server = http.createServer((req, res) => { + const page = pages[req.url]; + if (!page) { res.writeHead(404); res.end(); return; } + res.writeHead(200, { "Content-Type": page[0] }); res.end(page[1]); +}); +await new Promise(r => server.listen(0, "127.0.0.1", r)); +const base = `http://127.0.0.1:${server.address().port}`; + +const profile = fs.mkdtempSync(path.join(os.tmpdir(), "vjv-profile-")); +const context = await chromium.launchPersistentContext(profile, { + channel: "chromium", headless: true, + args: [`--disable-extensions-except=${ext}`, `--load-extension=${ext}`], + viewport: { width: 1280, height: 800 }, +}); +const step = s => console.log("[browser] " + s); +let failed = false; +try { + let [worker] = context.serviceWorkers(); + if (!worker) worker = await context.waitForEvent("serviceworker"); + const extId = worker.url().split("/")[2]; + const page = await context.newPage(); + const errors = []; + page.on("pageerror", e => errors.push(e.message)); + + step("A JSON page becomes the tree"); + await page.goto(base + "/data.json"); + await page.waitForSelector(".vjv .vjv-row"); + assert.equal(await page.locator("pre").first().isHidden(), true, "the raw text is hidden"); + const keys = await page.locator(".vjv-tree .vjv-key").allTextContents(); + for (const k of ['"user"', '"name"', '"orderId"', '"items"', '"sku"']) assert.ok(keys.includes(k), k); + + step("Big and exactly-written numbers are shown exactly"); + const nums = await page.locator(".vjv-tree .vjv-number").allTextContents(); + assert.ok(nums.includes("12345678901234567890"), nums.join(",")); + assert.ok(nums.includes("19.90")); + + step("Links are links, and only http(s)"); + assert.equal(await page.locator(".vjv-link").getAttribute("href"), "https://example.com/ada"); + + step("Clicking a value shows its path"); + await page.locator(".vjv-row", { hasText: '"email"' }).click(); + assert.equal(await page.locator(".vjv-path").textContent(), "$.user.email"); + + step("Search finds keys and values and walks through them"); + await page.fill(".vjv-search", "ada"); + await page.waitForFunction(() => document.querySelector(".vjv-hits")?.textContent.includes("of")); + assert.equal(await page.locator(".vjv-hits").textContent(), "1 of 3"); + await page.press(".vjv-search", "Enter"); + assert.equal(await page.locator(".vjv-hits").textContent(), "2 of 3"); + assert.equal(await page.locator(".vjv-path").textContent(), "$.user.email"); + + step("Collapse all and expand all"); + await page.click("text=Collapse all"); + assert.equal(await page.locator(".vjv-tree .vjv-row", { hasText: '"sku"' }).count() > 0 ? await page.locator(".vjv-tree .vjv-row", { hasText: '"sku"' }).first().isVisible() : false, false); + await page.click("text=Expand all"); + assert.equal(await page.locator(".vjv-tree .vjv-row", { hasText: '"sku"' }).first().isVisible(), true); + + step("Raw view: formatted, coloured, numbers exact"); + await page.click(".vjv-tab >> text=Raw"); + const raw = await page.locator(".vjv-raw").first().textContent(); + assert.ok(raw.includes('"orderId": 12345678901234567890') && raw.includes('"price": 19.90'), raw.slice(0, 200)); + assert.ok(await page.locator(".vjv-raw .vjv-t-key").count() > 5); + await page.selectOption(".vjv-select", "4"); + assert.ok((await page.locator(".vjv-raw").first().textContent()).includes('\n "user"'), "4-space indent"); + + step("The chosen view and indent are remembered"); + await page.reload(); + await page.waitForSelector(".vjv"); + assert.equal(await page.locator(".vjv-tab.vjv-on").textContent(), "Raw"); + assert.equal(await page.locator(".vjv-select").inputValue(), "4"); + await page.click(".vjv-tab >> text=Tree"); + + step("Plain text that is JSON is shown too; plain text that isn't is left alone"); + await page.goto(base + "/plain.txt"); await page.waitForSelector(".vjv"); + await page.goto(base + "/notjson.txt"); await page.waitForTimeout(400); + assert.equal(await page.locator(".vjv").count(), 0); + + step("A web page is never touched, even with JSON in a
");
+  await page.goto(base + "/page.html"); await page.waitForTimeout(400);
+  assert.equal(await page.locator(".vjv").count(), 0);
+
+  step("Broken JSON: where the mistake is, with the line marked");
+  await page.goto(base + "/broken.json"); await page.waitForSelector(".vjv-error");
+  assert.match(await page.locator(".vjv-error").textContent(), /line 4, column 1: There.s an extra comma/);
+  assert.equal(await page.locator(".vjv-line-bad .vjv-ln").textContent(), "4");
+
+  step("Anti-hijacking prefixes are handled");
+  await page.goto(base + "/xssi.json"); await page.waitForSelector(".vjv-row");
+  assert.ok((await page.locator(".vjv-tree").textContent()).includes('"safe"'));
+
+  step("JSON can't run anything: HTML stays text, javascript: isn't a link");
+  await page.goto(base + "/evil.json"); await page.waitForSelector(".vjv-row");
+  await page.waitForTimeout(300);
+  assert.equal(await page.evaluate(() => window.__pwned), undefined);
+  assert.equal(await page.locator(".vjv img").count(), 0);
+  assert.equal(await page.locator(".vjv-link").count(), 0);
+
+  step("5,000 rows: fast, and shown 200 at a time");
+  const t0 = Date.now();
+  await page.goto(base + "/big.json"); await page.waitForSelector(".vjv-row");
+  const ms = Date.now() - t0;
+  assert.ok(ms < 4000, `took ${ms} ms`);
+  assert.match(await page.locator(".vjv-showall").first().textContent(), /Show 200 more of 4,800/);
+  await page.fill(".vjv-search", "row 4321");
+  await page.waitForFunction(() => document.querySelector(".vjv-hits")?.textContent === "1 of 1");
+  assert.equal(await page.locator(".vjv-path").textContent(), "$.rows[4321].name");
+
+  step("The toolbar button's page: paste JSON and view it");
+  await page.goto(`chrome-extension://${extId}/src/viewer.html`);
+  await page.fill("#input", '{"pasted": [true, false]}');
+  await page.click("#view");
+  await page.waitForSelector(".vjv-row");
+  assert.ok((await page.locator(".vjv-tree").textContent()).includes('"pasted"'));
+  await page.click(".vjv-back");
+  await page.click("#sample");
+  await page.waitForSelector(".vjv-row");
+  assert.ok((await page.locator(".vjv-tree .vjv-number").allTextContents()).includes("9007199254740993123"));
+
+  assert.deepEqual(errors, [], "no page errors");
+  console.log("[browser] all checks passed");
+} catch (e) {
+  failed = true; console.error("[browser] FAILED:", e);
+} finally {
+  await context.close(); server.close();
+  try { fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 }); } catch { /* Chrome may still hold a file: the OS cleans temp */ }
+}
+process.exit(failed ? 1 : 0);
diff --git a/browser/json-viewer/test/core.test.mjs b/browser/json-viewer/test/core.test.mjs
new file mode 100644
index 0000000..50c1f84
--- /dev/null
+++ b/browser/json-viewer/test/core.test.mjs
@@ -0,0 +1,119 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+const V = createRequire(import.meta.url)("../src/core.js");
+
+test("knows JSON content types", () => {
+  for (const t of ["application/json", "application/json; charset=utf-8", "text/json", "application/ld+json", "application/vnd.api+json", "application/problem+json"]) assert.ok(V.isJsonType(t), t);
+  for (const t of ["text/html", "text/plain", "application/javascript", "", undefined]) assert.ok(!V.isJsonType(t), String(t));
+});
+
+test("spots JSON in plain text, and strips anti-hijacking prefixes", () => {
+  assert.ok(V.looksLikeJson('  {"a":1}\n'));
+  assert.ok(V.looksLikeJson("[1,2]"));
+  assert.ok(V.looksLikeJson(")]}',\n{\"a\":1}"));
+  assert.ok(!V.looksLikeJson("hello {world}"));
+  assert.deepEqual(V.stripPrefix("{}"), { body: "{}", prefix: "" });
+  assert.equal(V.stripPrefix("while(1);[1]").body, "[1]");
+  assert.equal(V.stripPrefix("for(;;);[1]").prefix, "for(;;);");
+});
+
+test("keeps big and exactly-written numbers exactly", () => {
+  const r = V.parse('{"id": 12345678901234567890, "price": 1.50, "n": 42, "f": 0.5, "e": 1e3}');
+  assert.ok(r.ok);
+  assert.ok(r.value.id instanceof V.Num);
+  assert.equal(r.value.id.source, "12345678901234567890");
+  assert.equal(String(r.value.price), "1.50");
+  assert.equal(r.value.n, 42);
+  assert.equal(r.value.f, 0.5);
+  assert.equal(V.stringify(r.value, 0), '{"id":12345678901234567890,"price":1.50,"n":42,"f":0.5,"e":1e3}');
+  assert.equal(V.kindOf(r.value.id), "number");
+});
+
+test("reports where broken JSON breaks", () => {
+  const text = '{\n  "a": 1,\n  "b": 2,\n}';
+  const r = V.parse(text);
+  assert.equal(r.ok, false);
+  assert.ok(r.where, "has a location");
+  assert.equal(r.where.line, 4);
+  const lead = V.parse('\n\n{"a": }');
+  assert.equal(lead.where.line, 3, "blank lines before the JSON still count");
+  assert.equal(V.parse("   ").ok, false);
+});
+
+test("parses with a prefix and remembers it", () => {
+  const r = V.parse(")]}'\n[1, 2]");
+  assert.ok(r.ok);
+  assert.deepEqual(r.value, [1, 2]);
+  assert.equal(r.prefix, ")]}'");
+});
+
+test("paths", () => {
+  assert.equal(V.pathOf([]), "$");
+  assert.equal(V.pathOf(["users", 2, "email"]), "$.users[2].email");
+  assert.equal(V.pathOf(["odd key", "$ok", "9x"]), '$["odd key"].$ok["9x"]');
+});
+
+test("formats with 2, 4 or tab indents, or on one line", () => {
+  const v = { a: [1, { b: null }], c: {}, d: [] };
+  assert.equal(V.stringify(v, 2), JSON.stringify(v, null, 2));
+  assert.equal(V.stringify(v, 4), JSON.stringify(v, null, 4));
+  assert.equal(V.stringify(v, "\t"), JSON.stringify(v, null, "\t"));
+  assert.equal(V.stringify(v, 0), JSON.stringify(v));
+  assert.equal(V.stringify("a\"b", 2), '"a\\"b"');
+});
+
+test("describes values", () => {
+  assert.equal(V.describe([1]), "1 item");
+  assert.equal(V.describe([1, 2]), "2 items");
+  assert.equal(V.describe({ a: 1 }), "1 key");
+  assert.equal(V.describe({}), "0 keys");
+  assert.equal(V.describe("x"), "string");
+});
+
+test("search finds keys and values, case-insensitively, in order", () => {
+  const v = { users: [{ name: "Ada", email: "ada@example.com" }, { name: "Linus", city: "Helsinki" }], Admin: true, big: new V.Num("98765432109876543210") };
+  assert.deepEqual(V.search(v, "ada"), [["users", 0, "name"], ["users", 0, "email"]]);
+  assert.deepEqual(V.search(v, "ADMIN"), [["Admin"]]);
+  assert.deepEqual(V.search(v, "876543"), [["big"]]);
+  assert.deepEqual(V.search(v, "  "), []);
+  assert.equal(V.search({ a: Array(50).fill("x") }, "x", 10).length, 10);
+});
+
+test("counts values, up to a cap", () => {
+  assert.equal(V.countNodes({ a: [1, 2], b: null }), 5);
+  assert.equal(V.countNodes(Array(1000).fill(1), 100), 100);
+});
+
+test("links are only http and https", () => {
+  assert.ok(V.isLink("https://example.com/a?b=1"));
+  assert.ok(!V.isLink("javascript:alert(1)"));
+  assert.ok(!V.isLink("https://a b"));
+  assert.ok(!V.isLink(42));
+});
+
+test("tokenizes pretty JSON for colouring, losing nothing", () => {
+  const text = V.stringify({ a: "x", n: -1.5e3, t: true, z: null, l: [1] }, 2);
+  const tokens = V.tokenize(text);
+  assert.equal(tokens.map(t => t[1]).join(""), text);
+  const types = tokens.filter(t => t[0] !== "space" && t[0] !== "punct").map(t => t[0]);
+  assert.deepEqual(types, ["key", "string", "key", "number", "key", "boolean", "key", "null", "key", "number"]);
+});
+
+test("the error scanner agrees with JSON.parse", () => {
+  const good = ['{"a":[1,2,{"b":null}],"c":"x\\n\\u00e9"}', "[]", "-0.5e+3", '"s"', "true", ' { } '];
+  for (const t of good) { assert.equal(V.errorOffset(t.trim()), -1, t); JSON.parse(t); }
+  const bad = [["{\"a\":1,}", 7], ["[1 2]", 3], ["{a:1}", 1], ["[01]", 2], ['"\\x"', 1], ["nul", 3], ["[1]x", 3], ["{\"a\" 1}", 5]];
+  for (const [t] of bad) assert.throws(() => JSON.parse(t), t);
+  for (const [t, at] of bad) assert.equal(V.errorOffset(t), at, t);
+  assert.deepEqual(V.lineColumn("ab\ncd", 4), { line: 2, column: 2 });
+});
+
+test("says the everyday mistakes plainly", () => {
+  assert.match(V.parse('{"a": 1,\n}').error, /extra comma before this }/);
+  assert.match(V.parse('[1, 2, ]').error, /extra comma before this ]/);
+  assert.match(V.parse("{'a': 1}").error, /double quotes/);
+  assert.match(V.parse('{name: "x"}').error, /Keys need double quotes/);
+  assert.match(V.parse('{"a": 1 "b": 2}').error, /comma is missing/);
+  assert.match(V.parse('{"a": [1, 2').error, /ends too early/);
+});
diff --git a/website/app/json-viewer/page.tsx b/website/app/json-viewer/page.tsx
new file mode 100644
index 0000000..b1f5bf3
--- /dev/null
+++ b/website/app/json-viewer/page.tsx
@@ -0,0 +1,116 @@
+import type {Metadata} from 'next';
+import Image from 'next/image';
+import Link from 'next/link';
+import {AlertTriangle,Binary,Copy,Download,FileUp,Github,Lock,Palette,Route,Search,ShieldCheck,TreePine,Zap} from 'lucide-react';
+import {Nav} from '@/components/Nav';
+import {Footer} from '@/components/Footer';
+import {Breadcrumbs} from '@/components/Breadcrumbs';
+import {ClosingCTA} from '@/components/ContentPage';
+import {absolute,jsonLd} from '@/lib/site';
+import '../live-server/live-server.css';
+import '../port-manager/port-manager.css';
+
+/** Set this to the Chrome Web Store link once the extension is published; until then the page offers the zip. */
+const CHROME_STORE_URL='';
+const VERSION='1.0.0';
+const ZIP=`https://github.com/fcopensource/veyraeditor/raw/main/browser/json-viewer/release/json-viewer-veyra-${VERSION}.zip`;
+const SOURCE='https://github.com/fcopensource/veyraeditor/tree/main/browser/json-viewer';
+
+export const metadata:Metadata={
+  title:'JSON Viewer for Chrome: Readable, Searchable JSON, Exact Numbers',
+  description:'A free Chrome extension that shows JSON as a clear, searchable tree. Exact big numbers, the path of every value, broken JSON explained with line numbers, raw and original views. Private: nothing is sent anywhere.',
+  keywords:['json viewer','chrome json viewer','json formatter','json formatter chrome','view json in browser','pretty print json','json tree viewer','json path','chrome extension'],
+  alternates:{canonical:'/json-viewer'},
+  openGraph:{url:'/json-viewer',title:'JSON Viewer Veyra for Chrome',description:'JSON as a clear, searchable tree. Exact numbers. Private.',images:[{url:'/json-viewer-tree.png',width:1280,height:800,alt:'The JSON Viewer tree in Chrome with a value selected and its path shown'}]},
+};
+
+const FEATURES=[
+  {icon:TreePine,title:'A tree you can read',copy:'Open and close any level, with a count of keys and items. Small files open fully; big ones show 200 items at a time, so a 10 MB response stays fast.'},
+  {icon:Binary,title:'Exact numbers',copy:'Long IDs like 9007199254740993123 and prices like 19.90 are shown exactly as sent. Most viewers round them without telling you.'},
+  {icon:Route,title:'The path of every value',copy:'Click a value to see $.items[0].price. Copy the path for your code, or copy the value.'},
+  {icon:Search,title:'Search everything',copy:'Keys and values, case-insensitive. Enter and Shift+Enter step through the matches; Ctrl+F jumps to the box.'},
+  {icon:AlertTriangle,title:'Mistakes, explained',copy:'Broken JSON shows the line and column, highlights the line, and says what’s wrong in plain words, like an extra comma before }.'},
+  {icon:Copy,title:'Raw, original, copy, download',copy:'A coloured raw view with 2 spaces, 4 spaces, tabs or one line, the text exactly as sent, and one-click copy or download.'},
+  {icon:FileUp,title:'Paste or open a file',copy:'Click the toolbar button to paste JSON or open a .json file, and get the same viewer.'},
+  {icon:Palette,title:'Dark, light or automatic',copy:'Follows your system, or pick one. Your view, indent and theme are remembered.'},
+  {icon:Lock,title:'Private by design',copy:'No network requests, no analytics, no account. JSON is shown as text only, so a document can never run code through the viewer.'},
+];
+const FAQ=[
+  {q:'Is it free?',a:'Yes. JSON Viewer Veyra is free and open source under the MIT license, with no ads, no account and no tracking.'},
+  {q:'Which pages does it change?',a:'Only pages that are JSON: a JSON content type such as application/json, or plain text that is valid JSON. Web pages are never touched.'},
+  {q:'Why does it need access to the pages I open?',a:'JSON can come from any website or API, so the extension checks each page’s content type. On anything that isn’t JSON it stops immediately and reads nothing.'},
+  {q:'What does “exact numbers” mean?',a:'JavaScript can only hold numbers up to about 16 digits exactly, so many viewers show 9007199254740993123 as 9007199254740993000, and 19.90 as 19.9. This viewer shows every number exactly as the server sent it.'},
+  {q:'Does it work with big files?',a:'Yes. It draws only what you open, 200 items at a time, so responses of many megabytes stay quick to scroll and search.'},
+  {q:'Does it work in Edge, Brave and other browsers?',a:'Yes, in any Chromium browser: Chrome, Edge, Brave, Opera, Vivaldi and Arc.'},
+];
+
+export default function JsonViewerPage(){
+  const published=!!CHROME_STORE_URL;
+  const app={
+    '@context':'https://schema.org','@type':'SoftwareApplication',name:'JSON Viewer Veyra',applicationCategory:'BrowserApplication',
+    operatingSystem:'Chrome, Edge, Brave and other Chromium browsers',url:absolute('/json-viewer'),image:absolute('/json-viewer-icon.png'),softwareVersion:VERSION,
+    downloadUrl:published?CHROME_STORE_URL:ZIP,license:'https://opensource.org/licenses/MIT',
+    description:'A free Chrome extension that shows JSON as a clear, searchable tree, with exact numbers and the path of every value.',
+    offers:{'@type':'Offer',price:'0',priceCurrency:'USD'},publisher:{'@type':'Organization',name:'FlightCoders',url:'https://flightcoders.com'},
+  };
+  const faq={'@context':'https://schema.org','@type':'FAQPage',mainEntity:FAQ.map(item=>({'@type':'Question',name:item.q,acceptedAnswer:{'@type':'Answer',text:item.a}}))};
+
+  return <>