feat: 2.1.0 — JSONC → JSON (#161)
JSONC (JSON with comments) converts to standard JSON as a new input-only format: hand-written parser, comments and trailing commas removed at the same offsets, token-level output that keeps every number and key as written. Input-only formats in the framework (meta.inputOnly), reverse errors with line/column, JSONC editor highlighting and lint, a one-click hint in the JSON → direction, strings in four locales, docs and the 2.1.0 version bump. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b148f91635
commit
e3d0e8b917
41 files changed
+936
-95
No files matched your search
@@ -8,6 +8,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
||||
|
||||
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
|
||||
|
||||
## [2.1.0] — 2026-10-29
|
||||
|
||||
### Added
|
||||
|
||||
- **JSONC → JSON.** A new input-only format for JSON with comments, such as `tsconfig.json`, VS Code `settings.json`, `.code-workspace` and `deno.jsonc` files. Pick **JSONC** in the **→ JSON** direction, paste or drop `.jsonc` and `.json` files (batches included), and get standard JSON back: `//` and `/* */` comments and trailing commas are removed. Values are copied token by token rather than through JavaScript numbers, so integers beyond 2^53, `1.0`, `1e3`, duplicate keys and `__proto__` come out exactly as written. Output layout: 2 spaces (default), 4 spaces, tab or minified. The parser is hand-written and runs on your device; there is no new dependency.
|
||||
- **"This looks like JSONC" hint.** In the JSON → direction, when the input fails only because of comments or trailing commas, the input panel offers **Convert JSONC → JSON**, which switches the direction and format in one click.
|
||||
- The JSONC input editor highlights comments and marks errors in the gutter at the same line and column the converter reports.
|
||||
|
||||
### Changed
|
||||
|
||||
- Converting back to JSON can now report the line and column of an error. JSONC uses it, so its errors show `Ln …, Col …` like JSON input errors do.
|
||||
- The JSONC chip is disabled in the JSON → direction with an "Input only" note. Switching to JSON → while JSONC is selected moves to JSONL.
|
||||
|
||||
## [2.0.2] — 2026-10-27
|
||||
|
||||
### Added
|
||||
|
||||
@@ -4,7 +4,7 @@ Guidance for Claude (and other AI assistants) working on this repository.
|
||||
|
||||
## Project context
|
||||
|
||||
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back. Conversion always runs on the user's device. It ships as:
|
||||
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back, plus the input-only JSONC → JSON. Conversion always runs on the user's device. It ships as:
|
||||
|
||||
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets behind a tiny Worker that rate limits requests and answers `/api/*`), deployed by Cloudflare Workers Builds on every push to `main`;
|
||||
- native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
|
||||
@@ -13,7 +13,7 @@ GitHub Pages (`poli0981.github.io/jsonPrism`) now only redirects to the new doma
|
||||
|
||||
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: the developer community on the open-source Discord server plus YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
|
||||
|
||||
**Current release**: 2.0.2. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
|
||||
**Current release**: 2.1.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
|
||||
|
||||
## Stack — exact versions matter
|
||||
|
||||
@@ -118,7 +118,7 @@ If you find yourself wanting another top-level folder, stop and reconsider.
|
||||
## Adding a new converter — checklist
|
||||
|
||||
1. Create `src/converters/myformat.ts` exporting `myFormatConverter`.
|
||||
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, and `binary` for byte formats). Return errors as values.
|
||||
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, `binary` for byte formats, and `inputOnly` for formats that only convert to JSON, like JSONC — their `convert()` returns an error). Return errors as values.
|
||||
3. Add the ID to the `FormatId` union in `src/converters/types.ts`.
|
||||
4. Register it in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`).
|
||||
5. Add `formats.myformat` (and any option labels) to all four locale files.
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAU
|
||||
|
||||
Briefly:
|
||||
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values)
|
||||
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values; an input-only format such as JSONC sets `meta.inputOnly`)
|
||||
2. Add the ID to `FormatId` in `types.ts` and register the converter in `registry.ts`
|
||||
3. Add `formats.myformat` labels to all four locales
|
||||
4. Add tests in `src/converters/__tests__/` (`contract.test.ts` already runs every registered converter against the errors-as-values contract)
|
||||
|
||||
+2
-1
@@ -59,7 +59,8 @@ do not depend on these services.
|
||||
without checking it.
|
||||
- Do not assume that a round trip JSON → format → JSON is byte-perfect for
|
||||
lossy formats. Only JSONL, CSV, TSV, YAML, TOML and RESX convert back
|
||||
to JSON at all.
|
||||
to JSON at all. JSONC → JSON removes comments and trailing commas, so
|
||||
they are not kept.
|
||||
- Pin a specific JSONPrism version if you depend on its behaviour; future
|
||||
releases may change defaults.
|
||||
|
||||
|
||||
@@ -20,22 +20,23 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
|
||||
|
||||
## Target formats
|
||||
|
||||
| Format | Extension | Status | Reverse (→ JSON) |
|
||||
| ----------------- | ----------- | ------------- | ---------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Markdown table | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
| Format | Extension | Status | Reverse (→ JSON) |
|
||||
| ------------------ | ----------------- | --------- | ---------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| JSONC (input only) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (only) |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Markdown table | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
|
||||
Twelve formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
|
||||
Twelve target formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. **JSONC** (JSON with comments: `tsconfig.json`, VS Code settings) is input only: it turns `.jsonc` and `.json` files into plain JSON, dropping comments and trailing commas while keeping every value, number and key exactly as written. Paste JSONC in the JSON → direction and the app offers to switch. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
};
|
||||
```
|
||||
|
||||
An input-only format (like JSONC) sets `meta.inputOnly: true`, implements `reverse()`, and has `convert()` return an error; the UI then disables it in the JSON → direction.
|
||||
|
||||
Then add the id to the `FormatId` union in `src/converters/types.ts`, register the converter in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`), and add its label keys to all four files in `src/i18n/locales/` — a parity test fails when a locale is missing a key.
|
||||
|
||||
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full phase plan.
|
||||
|
||||
+18
-15
@@ -20,22 +20,23 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
|
||||
|
||||
## Định dạng hỗ trợ
|
||||
|
||||
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
|
||||
| ----------------- | ------------ | -------------- | ------------ |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
|
||||
| ------------------- | ----------------- | ---------- | ----------------- |
|
||||
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
|
||||
| JSONC (chỉ đầu vào) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (chỉ chiều này) |
|
||||
| CSV | `.csv` | ✅ Phase 1 | ✅ |
|
||||
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
|
||||
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
|
||||
| XML | `.xml` | ✅ Phase 2 | — |
|
||||
| TOML | `.toml` | ✅ Phase 2 | ✅ |
|
||||
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
|
||||
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
|
||||
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
|
||||
| BSON | `.bson` | ✅ Phase 4 | — |
|
||||
| CBOR | `.cbor` | ✅ Phase 4 | — |
|
||||
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
|
||||
|
||||
Tổng cộng 12 định dạng. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
|
||||
Tổng cộng 12 định dạng đích. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. **JSONC** (JSON có comment: `tsconfig.json`, settings của VS Code) là định dạng chỉ-đầu-vào: biến file `.jsonc` và `.json` thành JSON thuần, bỏ comment và dấu phẩy thừa nhưng giữ nguyên mọi giá trị, con số và key như bạn viết. Dán JSONC ở chiều JSON → thì app sẽ gợi ý chuyển sang. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
|
||||
|
||||
## Tính năng
|
||||
|
||||
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
|
||||
};
|
||||
```
|
||||
|
||||
Định dạng chỉ-đầu-vào (như JSONC) đặt `meta.inputOnly: true`, cài `reverse()`, còn `convert()` trả lỗi; UI sẽ disable nó ở chiều JSON →.
|
||||
|
||||
Sau đó thêm id vào union `FormatId` trong `src/converters/types.ts`, đăng ký converter trong `src/converters/registry.ts` (`CONVERTERS` và `ALL_FORMATS`), và thêm label key vào cả bốn file trong `src/i18n/locales/` — test parity sẽ fail nếu một ngôn ngữ thiếu key.
|
||||
|
||||
Xem [`docs/ROADMAP.md`](docs/ROADMAP.md) để biết kế hoạch phase đầy đủ.
|
||||
|
||||
+21
-1
@@ -4,7 +4,7 @@ This document is the **single source of truth** for what's done, what's next, an
|
||||
|
||||
Update it as work lands — keep the project status honest.
|
||||
|
||||
**Current release: v2.0.2 (2026-10-27).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
|
||||
**Current release: v2.1.0 (2026-10-29).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
|
||||
|
||||
---
|
||||
|
||||
@@ -353,6 +353,25 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
|
||||
|
||||
---
|
||||
|
||||
## Phase 9 — 2.1.0: JSONC → JSON ✅
|
||||
|
||||
**Status**: complete (shipped in v2.1.0, 2026-10-29)
|
||||
|
||||
The most common "this isn't valid JSON" paste — config files with comments — now converts in one step.
|
||||
|
||||
- [x] `src/converters/jsonc.ts`: hand-written, no dependency. Comments and trailing commas become spaces at the same offsets (error line/column match the input), `JSON.parse` validates, then a token-level printer lays the result out without building JS values — big integers, number spelling, duplicate and `__proto__` keys survive. Iterative, with an output-size guard for pathological nesting.
|
||||
- [x] Input-only formats: `ConverterMeta.inputOnly`; the chip is disabled in the JSON → direction, switching to JSON → falls back to JSONL, and a stored input-only format opens in → JSON.
|
||||
- [x] Reverse errors carry an optional line/column (`ConversionFailure`), shown like JSON input errors.
|
||||
- [x] JSONC input editor: legacy JSON mode for comment highlighting plus a linter that shares the converter's parser.
|
||||
- [x] JSON → input that is valid JSONC gets a one-click "Convert JSONC → JSON" hint.
|
||||
- [x] Accepts `.jsonc` and `.json` (plus `.txt`) in the single-file and batch flows; strings in all four locales.
|
||||
|
||||
### Deliverable
|
||||
|
||||
13 chips — 12 target formats plus JSONC as an input. **932 tests in 94 files.**
|
||||
|
||||
---
|
||||
|
||||
## Beyond — Ideas (no commitment)
|
||||
|
||||
### Deferred from 2.0.0
|
||||
@@ -365,6 +384,7 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
|
||||
- **End-to-end tests** — Playwright (web), tauri-driver (desktop)
|
||||
- **JSON tools** — JSON Schema, JSONPath and diff features
|
||||
- **More formats** — INI, `.env`, Java `.properties`, Excel `.xlsx`
|
||||
- **JSONC as input for every target** — accept comments in the JSON → direction (e.g. `tsconfig.json` straight to YAML) instead of converting to JSON first; changes the strict `parseJsonInput` contract, so it needs its own design
|
||||
- **Streaming NDJSON** for very large files
|
||||
- **Community translation workflow** (ja and zh-CN are AI-translated today)
|
||||
- **Drop the TypeScript 6 alias** once TypeScript 7 ships an API that typescript-eslint supports
|
||||
|
||||
+3
-3
@@ -18,11 +18,11 @@
|
||||
<title>JSONPrism · Disperse JSON into 12 formats</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, and six of them back to JSON. Conversion runs on your device; batch up to 500 files."
|
||||
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, reads six of them back, and turns JSONC (JSON with comments) into plain JSON. Conversion runs on your device; batch up to 500 files."
|
||||
/>
|
||||
<meta
|
||||
name="keywords"
|
||||
content="JSON converter, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
|
||||
content="JSON converter, JSONC to JSON, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
|
||||
/>
|
||||
<!-- Updated per route by Layout (useCanonicalUrl). -->
|
||||
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
|
||||
@@ -33,7 +33,7 @@
|
||||
<meta property="og:title" content="JSONPrism — Disperse JSON into 12 formats" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible. Runs on your device."
|
||||
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible, plus JSONC to JSON. Runs on your device."
|
||||
/>
|
||||
<meta property="og:url" content="https://jsonprism.poli0981.dev/" />
|
||||
<meta property="og:image" content="https://jsonprism.poli0981.dev/og-image.png" />
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "jsonprism",
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"private": true,
|
||||
"version": "2.0.2",
|
||||
"version": "2.1.0",
|
||||
"type": "module",
|
||||
"description": "Disperse JSON into 12 formats (six convert back) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
|
||||
"description": "Disperse JSON into 12 formats (six convert back, plus JSONC → JSON) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
|
||||
"author": "poli0981 <code@poli0981.dev> (https://github.com/poli0981)",
|
||||
"license": "Apache-2.0",
|
||||
"homepage": "https://jsonprism.poli0981.dev",
|
||||
|
||||
Generated
+1
-1
@@ -1876,7 +1876,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jsonprism"
|
||||
version = "2.0.2"
|
||||
version = "2.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jsonprism"
|
||||
version = "2.0.2"
|
||||
version = "2.1.0"
|
||||
description = "Disperse JSON into many formats."
|
||||
authors = ["poli0981 <code@poli0981.dev>"]
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
By installing and using JSONPrism, you agree to the terms below.\par
|
||||
\par
|
||||
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
|
||||
https://github.com/poli0981/jsonPrism/blob/v2.0.2/LICENSE\par
|
||||
https://github.com/poli0981/jsonPrism/blob/v2.1.0/LICENSE\par
|
||||
\par
|
||||
Your use is also governed by the following documents (version 2.0, effective 2026-10-22):\par
|
||||
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.2/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.2/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.2/DISCLAIMER.md\par
|
||||
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.1.0/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.1.0/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.1.0/DISCLAIMER.md\par
|
||||
\par
|
||||
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. The desktop app converts everything on your device and makes no network requests of its own.\par
|
||||
\par
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
],
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "Disperse JSON into many formats",
|
||||
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back, entirely on your machine.",
|
||||
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back (plus JSONC into plain JSON), entirely on your machine.",
|
||||
"copyright": "Copyright (c) 2026 poli0981",
|
||||
"publisher": "poli0981",
|
||||
"homepage": "https://jsonprism.poli0981.dev",
|
||||
@@ -78,7 +78,7 @@
|
||||
},
|
||||
"android": {
|
||||
"minSdkVersion": 31,
|
||||
"versionCode": 20002
|
||||
"versionCode": 20100
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
|
||||
@@ -12,15 +12,18 @@ import { xml } from '@codemirror/lang-xml';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { sql } from '@codemirror/lang-sql';
|
||||
import { HighlightStyle, StreamLanguage, syntaxHighlighting } from '@codemirror/language';
|
||||
import { json as jsonStream } from '@codemirror/legacy-modes/mode/javascript';
|
||||
import { toml } from '@codemirror/legacy-modes/mode/toml';
|
||||
import { lintGutter, linter, type Diagnostic } from '@codemirror/lint';
|
||||
import { tags as t } from '@lezer/highlight';
|
||||
import { parseJsonInput } from '@/lib/detect';
|
||||
import { parseJsonc } from '@/converters/jsonc';
|
||||
import type { ConversionFailure } from '@/converters/types';
|
||||
import { parseJsonInput, type ParseFailure } from '@/lib/detect';
|
||||
import { useTheme } from '@/lib/theme';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type EditorLanguage =
|
||||
'json' | 'jsonl' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
'json' | 'jsonl' | 'jsonc' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
@@ -76,15 +79,23 @@ const yieldFileDrops = EditorView.domEventHandlers({
|
||||
const LINT_LIMIT_CHARS = 2_000_000;
|
||||
const MAX_JSONL_DIAGNOSTICS = 100;
|
||||
|
||||
type Check = (text: string) => { ok: true } | ParseFailure | ConversionFailure;
|
||||
|
||||
/**
|
||||
* Lints `text` (starting at document offset `start`) with the converter's own
|
||||
* parser, so the editor and the conversion agree — a leading byte-order mark
|
||||
* is fine, and error positions match on every engine. Blank text is a
|
||||
* prompt, not an error.
|
||||
*/
|
||||
function parseDiagnostic(view: EditorView, text: string, start: number): Diagnostic | null {
|
||||
const result = parseJsonInput(text);
|
||||
if (result.ok || result.error === 'empty') return null;
|
||||
function parseDiagnostic(
|
||||
view: EditorView,
|
||||
text: string,
|
||||
start: number,
|
||||
check: Check = parseJsonInput,
|
||||
): Diagnostic | null {
|
||||
if (!text.trim()) return null;
|
||||
const result = check(text);
|
||||
if (result.ok) return null;
|
||||
const { doc } = view.state;
|
||||
let from = start;
|
||||
if (result.line !== undefined && result.column !== undefined) {
|
||||
@@ -100,6 +111,17 @@ const jsonLint = linter((view) => {
|
||||
return diagnostic ? [diagnostic] : [];
|
||||
});
|
||||
|
||||
// @lezer/json has no comment tokens, so JSONC uses the legacy JSON mode, which
|
||||
// highlights them. It calls true/false/null "atom"; colour them like JSON's.
|
||||
const jsoncLanguage = StreamLanguage.define({ ...jsonStream, tokenTable: { atom: t.bool } });
|
||||
|
||||
// JSONC: comments and trailing commas are fine; the rest must be JSON.
|
||||
const jsoncLint = linter((view) => {
|
||||
if (view.state.doc.length > LINT_LIMIT_CHARS) return [];
|
||||
const diagnostic = parseDiagnostic(view, view.state.doc.toString(), 0, parseJsonc);
|
||||
return diagnostic ? [diagnostic] : [];
|
||||
});
|
||||
|
||||
// JSONL: every non-blank line is its own JSON document.
|
||||
const jsonlLint = linter((view) => {
|
||||
const { doc } = view.state;
|
||||
@@ -134,6 +156,8 @@ function languageExtensions(language: EditorLanguage, readOnly: boolean) {
|
||||
return readOnly ? [json()] : [json(), lintGutter(), jsonLint];
|
||||
case 'jsonl':
|
||||
return readOnly ? [json()] : [json(), lintGutter(), jsonlLint];
|
||||
case 'jsonc':
|
||||
return readOnly ? [jsoncLanguage] : [jsoncLanguage, lintGutter(), jsoncLint];
|
||||
case 'yaml':
|
||||
return [yaml()];
|
||||
case 'xml':
|
||||
|
||||
@@ -23,6 +23,8 @@ import { StatusBar, type ConversionState } from './StatusBar';
|
||||
import { BatchPanel } from './BatchPanel';
|
||||
|
||||
const REVERSIBLE_FALLBACKS: FormatId[] = ['jsonl', 'csv', 'yaml', 'toml', 'resx'];
|
||||
/** Where the JSON → direction lands when the current format is input-only. */
|
||||
const FORWARD_FALLBACK: FormatId = 'jsonl';
|
||||
|
||||
export function ConverterWorkspace() {
|
||||
const { t } = useTranslation();
|
||||
@@ -74,16 +76,24 @@ export function ConverterWorkspace() {
|
||||
(next: Direction) => {
|
||||
setDirection(next);
|
||||
// If the current format doesn't support the new direction, switch to one that does.
|
||||
if (next === 'reverse' && typeof getConverter(format).reverse !== 'function') {
|
||||
const converter = getConverter(format);
|
||||
if (next === 'reverse' && typeof converter.reverse !== 'function') {
|
||||
const fallback = REVERSIBLE_FALLBACKS.find(
|
||||
(id) => typeof getConverter(id).reverse === 'function',
|
||||
);
|
||||
if (fallback) setFormat(fallback);
|
||||
}
|
||||
if (next === 'forward' && converter.meta.inputOnly) setFormat(FORWARD_FALLBACK);
|
||||
},
|
||||
[format, setDirection, setFormat],
|
||||
);
|
||||
|
||||
// Offered by the input panel when JSON → fails on text that is valid JSONC.
|
||||
const readAsJsonc = useCallback(() => {
|
||||
setDirection('reverse');
|
||||
setFormat('jsonc');
|
||||
}, [setDirection, setFormat]);
|
||||
|
||||
const currentOptions = useMemo(
|
||||
() => storedOptions ?? { ...getConverter(format).defaultOptions },
|
||||
[format, storedOptions],
|
||||
@@ -130,6 +140,7 @@ export function ConverterWorkspace() {
|
||||
format={format}
|
||||
direction={direction}
|
||||
onMultiFileDrop={handleMultiFileDrop}
|
||||
onReadAsJsonc={readAsJsonc}
|
||||
/>
|
||||
);
|
||||
const outputPanel = (
|
||||
|
||||
@@ -13,7 +13,10 @@ interface FormatPickerProps {
|
||||
onChange: (id: FormatId) => void;
|
||||
/** Drives the subtle highlight ring on suggested chips. */
|
||||
shape?: JsonShape | null;
|
||||
/** When reverse, formats without a reverse() implementation are disabled. */
|
||||
/**
|
||||
* When reverse, formats without a reverse() implementation are disabled;
|
||||
* when forward, input-only formats (JSONC) are.
|
||||
*/
|
||||
direction?: Direction;
|
||||
}
|
||||
|
||||
@@ -30,7 +33,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
return (
|
||||
<>
|
||||
{/* Mobile: compact Sheet trigger — saves ~50-80px of toolbar height when
|
||||
the 12 chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
|
||||
the chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
|
||||
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<button
|
||||
@@ -70,7 +73,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* Desktop: 12 chips inline. */}
|
||||
{/* Desktop: every chip inline. */}
|
||||
<div
|
||||
className="hidden flex-wrap gap-1 md:flex"
|
||||
role="group"
|
||||
@@ -101,8 +104,9 @@ interface FormatChipProps {
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
function chipStatus(noReverse: boolean, suggested: boolean, dimmed: boolean) {
|
||||
function chipStatus(noReverse: boolean, inputOnly: boolean, suggested: boolean, dimmed: boolean) {
|
||||
if (noReverse) return 'no_reverse';
|
||||
if (inputOnly) return 'input_only';
|
||||
if (suggested) return 'suggested';
|
||||
return dimmed ? 'not_suggested' : 'ready';
|
||||
}
|
||||
@@ -113,9 +117,10 @@ function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatC
|
||||
const active = value === id;
|
||||
const suggested = direction === 'forward' && shape ? isFormatSuggested(id, shape) : false;
|
||||
const noReverse = direction === 'reverse' && typeof c.reverse !== 'function';
|
||||
const enabled = c.meta.ready && !noReverse;
|
||||
const dimmed = direction === 'forward' && !!shape && !suggested && c.meta.ready;
|
||||
const status = chipStatus(noReverse, suggested, dimmed);
|
||||
const inputOnly = direction === 'forward' && c.meta.inputOnly === true;
|
||||
const enabled = c.meta.ready && !noReverse && !inputOnly;
|
||||
const dimmed = direction === 'forward' && !!shape && !suggested && enabled;
|
||||
const status = chipStatus(noReverse, inputOnly, suggested, dimmed);
|
||||
|
||||
return (
|
||||
<button
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDropzone, type FileRejection } from 'react-dropzone';
|
||||
import { Eraser, FileText, FolderOpen } from 'lucide-react';
|
||||
import { Eraser, FileText, FolderOpen, MessageSquareCode } from 'lucide-react';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { parseJsonc } from '@/converters/jsonc';
|
||||
import { extensionsFor } from '@/converters/registry';
|
||||
import type { Direction, FormatId } from '@/converters/types';
|
||||
import { useFileAccept } from '@/hooks/useFileAccept';
|
||||
import { WORKER_THRESHOLD_CHARS } from '@/lib/convert-client';
|
||||
import { editorLanguageFor } from '@/lib/editor-language';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { extOf } from '@/lib/file-filter';
|
||||
@@ -28,6 +30,8 @@ interface InputPanelProps {
|
||||
direction: Direction;
|
||||
/** Called when 2+ files are dropped — workspace routes them into batch. */
|
||||
onMultiFileDrop?: (files: File[]) => void;
|
||||
/** Switches to JSONC → JSON; offered when JSON → fails on valid JSONC. */
|
||||
onReadAsJsonc?: () => void;
|
||||
}
|
||||
|
||||
export function InputPanel({
|
||||
@@ -39,6 +43,7 @@ export function InputPanel({
|
||||
format,
|
||||
direction,
|
||||
onMultiFileDrop,
|
||||
onReadAsJsonc,
|
||||
}: InputPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -156,6 +161,13 @@ export function InputPanel({
|
||||
if (file) loadFile(file);
|
||||
};
|
||||
|
||||
// Comments or trailing commas make JSON → fail; if that is all that is wrong,
|
||||
// offer JSONC. Inputs this big convert in the worker, so skip the extra parse.
|
||||
const looksLikeJsonc = useMemo(
|
||||
() => !isReverse && !!error && value.length < WORKER_THRESHOLD_CHARS && parseJsonc(value).ok,
|
||||
[error, isReverse, value],
|
||||
);
|
||||
|
||||
const showOverlay = isDragActive || dragActive;
|
||||
const position =
|
||||
errorLine != null
|
||||
@@ -219,6 +231,23 @@ export function InputPanel({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{looksLikeJsonc && onReadAsJsonc && (
|
||||
<div className="border-border/70 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b px-3 py-1 text-xs">
|
||||
<span className="text-muted-foreground">{t('home.jsonc_hint')}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onReadAsJsonc}
|
||||
className="group border-primary/40 text-foreground hover:bg-primary/10 focus-visible:ring-ring inline-flex min-h-6 items-center gap-1.5 rounded-md border px-2 font-mono font-medium transition outline-none focus-visible:ring-2"
|
||||
>
|
||||
<MessageSquareCode
|
||||
className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-rotate-6"
|
||||
aria-hidden
|
||||
/>
|
||||
{t('home.jsonc_switch')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<CodeEditorLazy
|
||||
value={value}
|
||||
|
||||
@@ -156,6 +156,7 @@ describe('CodeEditor — languages', () => {
|
||||
it.each<[EditorLanguage, string | null]>([
|
||||
['json', 'json'],
|
||||
['jsonl', 'json'],
|
||||
['jsonc', 'json'],
|
||||
['yaml', 'yaml'],
|
||||
['xml', 'xml'],
|
||||
['markdown', 'markdown'],
|
||||
@@ -218,6 +219,26 @@ describe('CodeEditor — JSON linting', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — JSONC linting', () => {
|
||||
const language = editorLanguageFor('jsonc', 'reverse');
|
||||
|
||||
it('accepts comments and trailing commas', async () => {
|
||||
const { view } = renderEditor({
|
||||
value: '{\n // note\n "a": [1, 2,], /* more */\n}',
|
||||
language,
|
||||
});
|
||||
expect(await lintNow(view)).toBe(0);
|
||||
});
|
||||
|
||||
it('flags JSONC errors where the converter does', async () => {
|
||||
const { view } = renderEditor({ value: '{\n "a": 1 /* open\n}', language });
|
||||
expect(await lintNow(view)).toBe(1);
|
||||
|
||||
typeInto(view, '');
|
||||
expect(await lintNow(view)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CodeEditor — behaviour', () => {
|
||||
it('leaves file drops to the surrounding dropzone', async () => {
|
||||
const { content, view } = renderEditor({ value: 'keep' });
|
||||
|
||||
@@ -195,6 +195,39 @@ describe('ConverterWorkspace — direction', () => {
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'csv' });
|
||||
expect(inputBox()).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('converts JSONC back to JSON and places errors in the original text', () => {
|
||||
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
|
||||
render(<ConverterWorkspace />);
|
||||
|
||||
type('{\n // comment\n "a": [1, 2,],\n}', 'Input JSONC');
|
||||
expect(outputBox('JSON output (read-only)')).toHaveValue('{\n "a": [\n 1,\n 2\n ]\n}');
|
||||
|
||||
type('{\n /* comment */\n "a": 1\n "b": 2\n}', 'Input JSONC');
|
||||
expect(screen.getByRole('status')).toHaveTextContent(/^Ln 4, Col 3/);
|
||||
expect(screen.getByText('error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('leaves an input-only format when switching to JSON →', async () => {
|
||||
const user = userEvent.setup();
|
||||
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
|
||||
render(<ConverterWorkspace />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'JSON →' }));
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'jsonl' });
|
||||
expect(within(chips()).getByRole('button', { name: 'JSONC' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('offers to read JSON with comments as JSONC', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ConverterWorkspace />);
|
||||
type('[1, /* two */ 2]');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
|
||||
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'reverse', format: 'jsonc' });
|
||||
expect(inputBox('Input JSONC')).toHaveValue('[1, /* two */ 2]');
|
||||
expect(outputBox('JSON output (read-only)')).toHaveValue('[\n 1,\n 2\n]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConverterWorkspace — options', () => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FormatPicker } from '../FormatPicker';
|
||||
|
||||
const LABELS: Record<FormatId, string> = {
|
||||
jsonl: 'JSONL',
|
||||
jsonc: 'JSONC',
|
||||
csv: 'CSV',
|
||||
tsv: 'TSV',
|
||||
yaml: 'YAML',
|
||||
@@ -34,7 +35,7 @@ describe('FormatPicker — inline chips', () => {
|
||||
render(<FormatPicker value="yaml" onChange={() => {}} />);
|
||||
const buttons = within(inlineGroup()).getAllByRole('button');
|
||||
expect(buttons.map((b) => b.textContent)).toEqual(Object.values(LABELS));
|
||||
for (const button of buttons) {
|
||||
for (const button of buttons.filter((b) => b.textContent !== 'JSONC')) {
|
||||
expect(button).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
button.textContent === 'YAML' ? 'true' : 'false',
|
||||
@@ -44,6 +45,23 @@ describe('FormatPicker — inline chips', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('disables input-only formats going forward', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
render(<FormatPicker value="jsonl" onChange={onChange} shape="object" />);
|
||||
|
||||
expect(chip('jsonc')).toBeDisabled();
|
||||
expect(chip('jsonc')).toHaveAttribute(
|
||||
'title',
|
||||
'Input only: converts to JSON in the → JSON direction',
|
||||
);
|
||||
// Disabled, not "not suggested": no dashed border.
|
||||
expect(chip('jsonc')).not.toHaveClass('border-dashed');
|
||||
|
||||
await user.click(chip('jsonc'));
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the picked format', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
@@ -84,8 +102,9 @@ describe('FormatPicker — inline chips', () => {
|
||||
expect(chip(format)).toBeDisabled();
|
||||
expect(chip(format)).toHaveAttribute('title', 'Reverse parse not supported for this format');
|
||||
}
|
||||
for (const format of ['jsonl', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
|
||||
for (const format of ['jsonl', 'jsonc', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
|
||||
expect(chip(format)).toBeEnabled();
|
||||
expect(chip(format)).toHaveAttribute('title', 'Ready');
|
||||
}
|
||||
|
||||
await user.click(chip('xml'));
|
||||
@@ -107,7 +126,7 @@ describe('FormatPicker — compact sheet (mobile)', () => {
|
||||
await user.click(screen.getByRole('button', { name: /Target format\s*JSONL/ }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Target format' });
|
||||
const sheetGroup = within(dialog).getByRole('group', { name: 'Target format' });
|
||||
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(12);
|
||||
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(13);
|
||||
expect(chip('jsonl', sheetGroup)).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(chip('yaml', sheetGroup)).toHaveAttribute('title', 'Suggested for the detected shape');
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ interface PanelProps {
|
||||
format?: FormatId;
|
||||
direction?: Direction;
|
||||
onMultiFileDrop?: (files: File[]) => void;
|
||||
onReadAsJsonc?: () => void;
|
||||
}
|
||||
|
||||
function renderPanel(props: PanelProps = {}) {
|
||||
@@ -54,6 +55,7 @@ function renderPanel(props: PanelProps = {}) {
|
||||
format={props.format ?? 'csv'}
|
||||
direction={props.direction ?? 'forward'}
|
||||
{...(props.onMultiFileDrop ? { onMultiFileDrop: props.onMultiFileDrop } : {})}
|
||||
{...(props.onReadAsJsonc ? { onReadAsJsonc: props.onReadAsJsonc } : {})}
|
||||
/>,
|
||||
);
|
||||
const root = utils.container.firstElementChild as HTMLElement;
|
||||
@@ -113,6 +115,15 @@ describe('InputPanel — layout', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('highlights and accepts JSONC going back', () => {
|
||||
const { fileInput } = renderPanel({ format: 'jsonc', direction: 'reverse' });
|
||||
expect(screen.getByRole('textbox', { name: 'Input JSONC' })).toHaveAttribute(
|
||||
'data-language',
|
||||
'jsonc',
|
||||
);
|
||||
expect(fileInput).toHaveAttribute('accept', '.jsonc,.json,.txt,application/jsonc');
|
||||
});
|
||||
|
||||
it('passes edits straight through', () => {
|
||||
const { onChange } = renderPanel();
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Input JSON' }), {
|
||||
@@ -174,6 +185,38 @@ describe('InputPanel — error banner', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputPanel — JSONC hint', () => {
|
||||
const jsonc = '{\n // compiler options\n "strict": true,\n}';
|
||||
const error = "Expected property name or '}' in JSON";
|
||||
|
||||
it('offers JSONC → JSON when the JSON error is only comments or trailing commas', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onReadAsJsonc = vi.fn();
|
||||
renderPanel({ value: jsonc, error, onReadAsJsonc });
|
||||
|
||||
expect(
|
||||
screen.getByText('This looks like JSONC — JSON with comments or trailing commas.'),
|
||||
).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
|
||||
expect(onReadAsJsonc).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each<[string, PanelProps]>([
|
||||
['the input is valid', { value: jsonc, error: null }],
|
||||
['the text is not valid JSONC either', { value: '{"a": }', error }],
|
||||
['already converting back', { value: jsonc, error, direction: 'reverse', format: 'jsonc' }],
|
||||
['the input is too big to check here', { value: jsonc + ' '.repeat(256 * 1024), error }],
|
||||
])('stays hidden when %s', (_case, props) => {
|
||||
renderPanel({ ...props, onReadAsJsonc: vi.fn() });
|
||||
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('stays hidden without a handler', () => {
|
||||
renderPanel({ value: jsonc, error });
|
||||
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputPanel — file picker (web)', () => {
|
||||
it('opens the hidden file input', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -37,6 +37,12 @@ const ADVERSARIAL_TEXT = [
|
||||
'\u0000\u0001\u0002',
|
||||
'key = = value',
|
||||
'<root><data name="x"><value>1</value></data></root>',
|
||||
// JSONC-shaped: comments, stray commas, a string cut off mid-escape.
|
||||
'/*',
|
||||
'//',
|
||||
'[,]',
|
||||
'{"a": 1,} // ok',
|
||||
'"\\',
|
||||
];
|
||||
|
||||
describe('converter contract', () => {
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { ConversionResult } from '../types';
|
||||
import { jsoncConverter, parseJsonc } from '../jsonc';
|
||||
|
||||
type Indent = (typeof jsoncConverter.defaultOptions)['indent'];
|
||||
|
||||
function reverse(text: string, indent: Indent = '2'): ConversionResult {
|
||||
return jsoncConverter.reverse!({ text }, { indent });
|
||||
}
|
||||
|
||||
function ok(result: ConversionResult): string {
|
||||
if (!result.ok) throw new Error(`expected ok, got error: ${result.error}`);
|
||||
return result.output;
|
||||
}
|
||||
|
||||
function fail(result: ConversionResult) {
|
||||
if (result.ok) throw new Error(`expected an error, got output: ${result.output.slice(0, 200)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
describe('jsoncConverter — comments', () => {
|
||||
it('removes line and block comments', () => {
|
||||
const text = `// leading
|
||||
{
|
||||
"a": 1, // trailing
|
||||
/* block */ "b": [true, /* inline */ null]
|
||||
}
|
||||
/* end */`;
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: 1, b: [true, null] });
|
||||
});
|
||||
|
||||
it('ends a line comment at CR or LF and keeps the rest', () => {
|
||||
expect(JSON.parse(ok(reverse('[1, // one\r\n2, // two\r3]')))).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('keeps comment-like text inside strings', () => {
|
||||
const text = '{"url": "http://example.com/*x*/", "path": "C:\\\\dir\\\\", "q": "a\\"//b"} // c';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({
|
||||
url: 'http://example.com/*x*/',
|
||||
path: 'C:\\dir\\',
|
||||
q: 'a"//b',
|
||||
});
|
||||
});
|
||||
|
||||
it('reports an unterminated block comment where it starts', () => {
|
||||
const result = fail(reverse('{\n "a": 1 /* open\n}'));
|
||||
expect(result.error).toMatch(/Unterminated block comment/);
|
||||
expect(result).toMatchObject({ line: 2, column: 10 });
|
||||
});
|
||||
|
||||
it('rejects input that only has comments', () => {
|
||||
expect(fail(reverse('// nothing\n/* here */')).error).toMatch(/No JSON value/);
|
||||
expect(fail(reverse('')).error).toMatch(/No JSON value/);
|
||||
});
|
||||
|
||||
it('reports an unterminated string, even with comments after it', () => {
|
||||
expect(fail(reverse('["abc\n// x\n"]'))).toMatchObject({ line: 1 });
|
||||
expect(fail(reverse('["abc // x'))).toMatchObject({ line: 1 });
|
||||
});
|
||||
|
||||
it('leaves a lone slash for JSON.parse to reject', () => {
|
||||
expect(fail(reverse('[1 / 2]')).error.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — trailing commas', () => {
|
||||
it('removes trailing commas in objects, arrays and nested containers', () => {
|
||||
const text = '{"a": [1, 2,], "b": {"c": 3,},}';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: [1, 2], b: { c: 3 } });
|
||||
});
|
||||
|
||||
it('removes a trailing comma with comments and line breaks before the bracket', () => {
|
||||
const text = '[\n "x", // last item\n /* nothing more */\n]';
|
||||
expect(JSON.parse(ok(reverse(text)))).toEqual(['x']);
|
||||
});
|
||||
|
||||
it.each(['[,]', '{,}', '[1,,2]', '[1,,]', '{"a":,}'])('still rejects %s', (text) => {
|
||||
expect(fail(reverse(text)).error.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — errors line up with the input', () => {
|
||||
it('reports a JSON error at its line and column despite earlier comments', () => {
|
||||
const text = '/* a\n b */\n{\n "a": 1 // ok\n "b": 2\n}';
|
||||
expect(fail(reverse(text))).toMatchObject({ line: 5, column: 3 });
|
||||
});
|
||||
|
||||
it('counts columns in UTF-16 code units, like the editor', () => {
|
||||
const text = '/* 🎮 */ [1 2]';
|
||||
expect(fail(reverse(text))).toMatchObject({ line: 1, column: 13 });
|
||||
});
|
||||
|
||||
it('accepts a byte-order mark', () => {
|
||||
expect(ok(reverse('\uFEFF// bom\n[1]'))).toBe('[\n 1\n]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — output keeps values exactly', () => {
|
||||
it('copies number literals verbatim', () => {
|
||||
const output = ok(reverse('[12345678901234567890, 1.0, 1e3, -0, 0.1e-7]', 'minify'));
|
||||
expect(output).toBe('[12345678901234567890,1.0,1e3,-0,0.1e-7]');
|
||||
});
|
||||
|
||||
it('keeps duplicate and __proto__ keys', () => {
|
||||
const output = ok(reverse('{"a": 1, "a": 2, "__proto__": {"x": 1}}', 'minify'));
|
||||
expect(output).toBe('{"a":1,"a":2,"__proto__":{"x":1}}');
|
||||
});
|
||||
|
||||
it('collapses empty containers, comments inside included', () => {
|
||||
expect(ok(reverse('{ /* nothing */ "a": [ ], "b": { // none\n } }'))).toBe(
|
||||
'{\n "a": [],\n "b": {}\n}',
|
||||
);
|
||||
});
|
||||
|
||||
it('formats scalars at the root', () => {
|
||||
expect(ok(reverse('/* answer */ 42'))).toBe('42');
|
||||
expect(ok(reverse('"text" // c'))).toBe('"text"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — layout', () => {
|
||||
const text = '{"a": [1, {"b": null}], "c": "d"} // c';
|
||||
|
||||
it.each<[Indent, string]>([
|
||||
['2', '{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}'],
|
||||
[
|
||||
'4',
|
||||
'{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}',
|
||||
],
|
||||
['tab', '{\n\t"a": [\n\t\t1,\n\t\t{\n\t\t\t"b": null\n\t\t}\n\t],\n\t"c": "d"\n}'],
|
||||
['minify', '{"a":[1,{"b":null}],"c":"d"}'],
|
||||
])('indent %s', (indent, expected) => {
|
||||
expect(ok(reverse(text, indent))).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles deep nesting without recursion', () => {
|
||||
const depth = 10_000;
|
||||
const text = '['.repeat(depth) + '/* deep */' + ']'.repeat(depth);
|
||||
const output = ok(reverse(text, 'minify'));
|
||||
expect(output).toBe('['.repeat(depth - 1) + '[]' + ']'.repeat(depth - 1));
|
||||
});
|
||||
|
||||
it('refuses pretty output that would be enormous', () => {
|
||||
const depth = 50_000;
|
||||
const text = '['.repeat(depth) + '1' + ']'.repeat(depth);
|
||||
expect(fail(reverse(text)).error).toMatch(/too large/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsoncConverter — contract', () => {
|
||||
it('is input-only and has no forward pass', () => {
|
||||
expect(jsoncConverter.meta.inputOnly).toBe(true);
|
||||
const result = jsoncConverter.convert({ data: { a: 1 } }, jsoncConverter.defaultOptions);
|
||||
expect(result.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts .jsonc and .json files', () => {
|
||||
expect(jsoncConverter.meta.extension).toBe('jsonc');
|
||||
expect(jsoncConverter.meta.altExtensions).toEqual(['json']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseJsonc', () => {
|
||||
it('returns JSON text at the same offsets as the input', () => {
|
||||
const text = '{"a": 1, /* c */ "b": [2,],} // end';
|
||||
const result = parseJsonc(text);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.json).toHaveLength(text.length);
|
||||
expect(result.json).toBe(`{"a": 1, ${' '.repeat(7)} "b": [2 ] } ${' '.repeat(6)}`);
|
||||
expect(JSON.parse(result.json)).toEqual({ a: 1, b: [2] });
|
||||
});
|
||||
|
||||
it('returns plain JSON unchanged', () => {
|
||||
const text = '{"a": [1, 2]}';
|
||||
expect(parseJsonc(text)).toEqual({ ok: true, json: text });
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,12 @@ import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
|
||||
import type { FormatId } from '../types';
|
||||
|
||||
describe('converter registry', () => {
|
||||
it('exposes all 12 format IDs', () => {
|
||||
expect(ALL_FORMATS).toHaveLength(12);
|
||||
it('exposes all 13 format IDs', () => {
|
||||
expect(ALL_FORMATS).toHaveLength(13);
|
||||
expect(new Set(ALL_FORMATS)).toEqual(
|
||||
new Set<FormatId>([
|
||||
'jsonl',
|
||||
'jsonc',
|
||||
'csv',
|
||||
'tsv',
|
||||
'yaml',
|
||||
@@ -42,7 +43,7 @@ describe('converter registry', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('all 12 converters are marked ready', () => {
|
||||
it('all 13 converters are marked ready', () => {
|
||||
for (const id of ALL_FORMATS) {
|
||||
expect(getConverter(id).meta.ready).toBe(true);
|
||||
}
|
||||
@@ -50,7 +51,13 @@ describe('converter registry', () => {
|
||||
|
||||
it('phase metadata covers all expected phases', () => {
|
||||
const phases = ALL_FORMATS.map((id) => getConverter(id).meta.phase);
|
||||
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack.
|
||||
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack/jsonc.
|
||||
expect(new Set(phases)).toEqual(new Set([1, 2, 3, 4]));
|
||||
});
|
||||
|
||||
it('only JSONC is input-only, and it parses back to JSON', () => {
|
||||
const inputOnly = ALL_FORMATS.filter((id) => getConverter(id).meta.inputOnly);
|
||||
expect(inputOnly).toEqual(['jsonc']);
|
||||
expect(typeof getConverter('jsonc').reverse).toBe('function');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
import type { ConversionFailure, Converter } from './types';
|
||||
import { errorPosition, offsetToLineColumn } from '@/lib/detect';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
|
||||
type JsoncIndent = '2' | '4' | 'tab' | 'minify';
|
||||
|
||||
interface JsoncOptions {
|
||||
/** Layout of the JSON output; `minify` puts it on one line. */
|
||||
indent: JsoncIndent;
|
||||
}
|
||||
|
||||
const INDENT_UNITS: Record<JsoncIndent, string | null> = {
|
||||
'2': ' ',
|
||||
'4': ' ',
|
||||
tab: '\t',
|
||||
minify: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Formatted output beyond this many characters is refused: deep nesting makes
|
||||
* indentation grow quadratically, and engines cap strings near 2^29.
|
||||
*/
|
||||
const MAX_OUTPUT_CHARS = 2 ** 28;
|
||||
|
||||
const QUOTE = 0x22;
|
||||
const SLASH = 0x2f;
|
||||
const STAR = 0x2a;
|
||||
const BACKSLASH = 0x5c;
|
||||
const COMMA = 0x2c;
|
||||
const COLON = 0x3a;
|
||||
const LF = 0x0a;
|
||||
const CR = 0x0d;
|
||||
const OPEN_BRACE = 0x7b;
|
||||
const CLOSE_BRACE = 0x7d;
|
||||
const OPEN_BRACKET = 0x5b;
|
||||
const CLOSE_BRACKET = 0x5d;
|
||||
|
||||
/** Characters that end a number or `true`/`false`/`null` literal. */
|
||||
const DELIMITERS = ' \t\r\n{}[],:';
|
||||
|
||||
function isJsonWhitespace(c: number): boolean {
|
||||
return c === 0x20 || c === 0x09 || c === LF || c === CR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index just past the string literal opening at `start`. An unterminated
|
||||
* string stops at the end of its line; JSON.parse reports it later.
|
||||
*/
|
||||
function skipString(text: string, start: number): number {
|
||||
let i = start + 1;
|
||||
while (i < text.length) {
|
||||
const c = text.charCodeAt(i);
|
||||
if (c === QUOTE) return i + 1;
|
||||
if (c === LF || c === CR) return i;
|
||||
i += c === BACKSLASH ? 2 : 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
function skipWhitespace(text: string, start: number): number {
|
||||
let i = start;
|
||||
while (i < text.length && isJsonWhitespace(text.charCodeAt(i))) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* End of the comment starting at `start`: `start` itself when there is no
|
||||
* comment there, -1 for a block comment that never closes.
|
||||
*/
|
||||
function commentEnd(text: string, start: number): number {
|
||||
const next = text.charCodeAt(start + 1);
|
||||
if (next === SLASH) {
|
||||
let i = start + 2;
|
||||
while (i < text.length && text.charCodeAt(i) !== LF && text.charCodeAt(i) !== CR) i++;
|
||||
return i;
|
||||
}
|
||||
if (next === STAR) {
|
||||
const close = text.indexOf('*/', start + 2);
|
||||
return close < 0 ? -1 : close + 2;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every comment with spaces, keeping line breaks, so offsets — and
|
||||
* the line/column of any later JSON error — still match the user's text.
|
||||
* Returns the offset of an unterminated block comment instead.
|
||||
*/
|
||||
function blankComments(text: string): string | number {
|
||||
const parts: string[] = [];
|
||||
let copied = 0;
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const c = text.charCodeAt(i);
|
||||
if (c === QUOTE) {
|
||||
i = skipString(text, i);
|
||||
continue;
|
||||
}
|
||||
const end = c === SLASH ? commentEnd(text, i) : i;
|
||||
if (end < 0) return i;
|
||||
if (end === i) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
parts.push(text.slice(copied, i), text.slice(i, end).replace(/[^\r\n]/g, ' '));
|
||||
copied = end;
|
||||
i = end;
|
||||
}
|
||||
if (copied === 0) return text;
|
||||
parts.push(text.slice(copied));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** A comma after `[`, `{`, `,` or `:` is a syntax error, never a trailing comma. */
|
||||
function followsValue(previous: number): boolean {
|
||||
return (
|
||||
previous !== OPEN_BRACKET && previous !== OPEN_BRACE && previous !== COMMA && previous !== COLON
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces each comma that directly precedes `]` or `}` with a space. */
|
||||
function blankTrailingCommas(json: string): string {
|
||||
const commas: number[] = [];
|
||||
let pending = -1;
|
||||
let previous = OPEN_BRACKET;
|
||||
let i = 0;
|
||||
while (i < json.length) {
|
||||
const c = json.charCodeAt(i);
|
||||
if (isJsonWhitespace(c)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (pending >= 0 && (c === CLOSE_BRACKET || c === CLOSE_BRACE)) commas.push(pending);
|
||||
pending = c === COMMA && followsValue(previous) ? i : -1;
|
||||
previous = c;
|
||||
i = c === QUOTE ? skipString(json, i) : i + 1;
|
||||
}
|
||||
if (commas.length === 0) return json;
|
||||
const parts: string[] = [];
|
||||
let copied = 0;
|
||||
for (const at of commas) {
|
||||
parts.push(json.slice(copied, at), ' ');
|
||||
copied = at + 1;
|
||||
}
|
||||
parts.push(json.slice(copied));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
function failAt(error: string, text: string, offset: number): ConversionFailure {
|
||||
return { ok: false, error, ...offsetToLineColumn(text, offset) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns JSONC into plain JSON text at the same offsets: comments and trailing
|
||||
* commas become spaces, then JSON.parse validates the rest. Shared by the
|
||||
* converter and the input editor's linter so both report the same errors.
|
||||
*/
|
||||
export function parseJsonc(text: string): { ok: true; json: string } | ConversionFailure {
|
||||
// JSON.parse rejects a byte-order mark; a space keeps the offsets.
|
||||
const source = text.charCodeAt(0) === 0xfeff ? ' ' + text.slice(1) : text;
|
||||
const uncommented = blankComments(source);
|
||||
if (typeof uncommented === 'number') {
|
||||
return failAt('Unterminated block comment: add the closing */.', source, uncommented);
|
||||
}
|
||||
const json = blankTrailingCommas(uncommented);
|
||||
if (skipWhitespace(json, 0) === json.length) {
|
||||
return { ok: false, error: 'No JSON value: the input is empty or only has comments.' };
|
||||
}
|
||||
try {
|
||||
JSON.parse(json);
|
||||
return { ok: true, json };
|
||||
} catch (err) {
|
||||
const message = errorMessage(err);
|
||||
const position = errorPosition(message, json);
|
||||
return position ? { ok: false, error: message, ...position } : { ok: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** End of the string, number or literal token starting at `start`. */
|
||||
function valueEnd(json: string, start: number): number {
|
||||
if (json.charCodeAt(start) === QUOTE) return skipString(json, start);
|
||||
let i = start + 1;
|
||||
while (i < json.length && !DELIMITERS.includes(json[i]!)) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out valid JSON token by token. Tokens are copied verbatim — numbers
|
||||
* keep every digit, duplicate and `__proto__` keys survive — because no JS
|
||||
* value is built. Iterative, so deep nesting cannot overflow the stack.
|
||||
* Returns null when the output would be too large.
|
||||
*/
|
||||
function reprint(json: string, unit: string | null): string | null {
|
||||
const out: string[] = [];
|
||||
const colon = unit === null ? ':' : ': ';
|
||||
// Line breaks slice one shared indent string instead of repeating per line.
|
||||
let indent = '';
|
||||
const newline = (depth: number): string => {
|
||||
if (unit === null) return '';
|
||||
const width = depth * unit.length;
|
||||
if (indent.length < width) indent = unit.repeat(depth * 2);
|
||||
return '\n' + indent.slice(0, width);
|
||||
};
|
||||
let size = 0;
|
||||
let depth = 0;
|
||||
let i = skipWhitespace(json, 0);
|
||||
while (i < json.length) {
|
||||
const ch = json[i]!;
|
||||
let end = i + 1;
|
||||
let piece: string;
|
||||
switch (ch) {
|
||||
case '{':
|
||||
case '[': {
|
||||
const next = skipWhitespace(json, end);
|
||||
if (json[next] === (ch === '{' ? '}' : ']')) {
|
||||
piece = ch + json[next];
|
||||
end = next + 1;
|
||||
} else {
|
||||
depth++;
|
||||
piece = ch + newline(depth);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case '}':
|
||||
case ']':
|
||||
depth--;
|
||||
piece = newline(depth) + ch;
|
||||
break;
|
||||
case ',':
|
||||
piece = ',' + newline(depth);
|
||||
break;
|
||||
case ':':
|
||||
piece = colon;
|
||||
break;
|
||||
default:
|
||||
end = valueEnd(json, i);
|
||||
piece = json.slice(i, end);
|
||||
}
|
||||
size += piece.length;
|
||||
if (size > MAX_OUTPUT_CHARS) return null;
|
||||
out.push(piece);
|
||||
i = skipWhitespace(json, end);
|
||||
}
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* JSONC (JSON with Comments — tsconfig.json, VS Code settings) → JSON. An
|
||||
* input-only format: JSON is already valid JSONC, so there is no forward pass.
|
||||
*/
|
||||
export const jsoncConverter: Converter<JsoncOptions> = {
|
||||
meta: {
|
||||
id: 'jsonc',
|
||||
labelKey: 'formats.jsonc',
|
||||
extension: 'jsonc',
|
||||
// Most JSONC files are named .json (tsconfig.json, settings.json).
|
||||
altExtensions: ['json'],
|
||||
mimeType: 'application/jsonc',
|
||||
phase: 4,
|
||||
ready: true,
|
||||
inputOnly: true,
|
||||
},
|
||||
defaultOptions: { indent: '2' },
|
||||
optionSchema: [
|
||||
{
|
||||
type: 'enum',
|
||||
key: 'indent',
|
||||
labelKey: 'options.jsonc.indent',
|
||||
descriptionKey: 'options.jsonc.indent_desc',
|
||||
choices: [
|
||||
{ value: '2', labelKey: 'options.jsonc.indent_2' },
|
||||
{ value: '4', labelKey: 'options.jsonc.indent_4' },
|
||||
{ value: 'tab', labelKey: 'options.jsonc.indent_tab' },
|
||||
{ value: 'minify', labelKey: 'options.jsonc.indent_minify' },
|
||||
],
|
||||
},
|
||||
],
|
||||
convert() {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'JSONC is an input format: switch the direction to → JSON to convert it.',
|
||||
};
|
||||
},
|
||||
reverse({ text }, { indent }) {
|
||||
const parsed = parseJsonc(text);
|
||||
if (!parsed.ok) return parsed;
|
||||
const output = reprint(parsed.json, INDENT_UNITS[indent]);
|
||||
return output === null
|
||||
? {
|
||||
ok: false,
|
||||
error: 'The formatted JSON is too large (very deep nesting). Choose "Minified".',
|
||||
}
|
||||
: { ok: true, output };
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ConversionInput, ConversionResult, Converter, FormatId, ReverseInput } from './types';
|
||||
import { errorMessage } from '@/lib/errors';
|
||||
import { jsonlConverter } from './jsonl';
|
||||
import { jsoncConverter } from './jsonc';
|
||||
import { csvConverter, tsvConverter } from './csv';
|
||||
import { yamlConverter } from './yaml';
|
||||
import { xmlConverter } from './xml';
|
||||
@@ -15,6 +16,7 @@ import { msgpackConverter } from './msgpack';
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const CONVERTERS: Record<FormatId, Converter<any>> = {
|
||||
jsonl: jsonlConverter,
|
||||
jsonc: jsoncConverter,
|
||||
csv: csvConverter,
|
||||
tsv: tsvConverter,
|
||||
yaml: yamlConverter,
|
||||
@@ -30,6 +32,7 @@ export const CONVERTERS: Record<FormatId, Converter<any>> = {
|
||||
|
||||
export const ALL_FORMATS: FormatId[] = [
|
||||
'jsonl',
|
||||
'jsonc',
|
||||
'csv',
|
||||
'tsv',
|
||||
'yaml',
|
||||
|
||||
+15
-1
@@ -9,6 +9,7 @@
|
||||
|
||||
export type FormatId =
|
||||
| 'jsonl'
|
||||
| 'jsonc'
|
||||
| 'csv'
|
||||
| 'tsv'
|
||||
| 'yaml'
|
||||
@@ -43,6 +44,11 @@ export interface ConverterMeta {
|
||||
* for display, but downloads decode back to raw bytes via the MIME type.
|
||||
*/
|
||||
binary?: boolean;
|
||||
/**
|
||||
* Input-only formats (JSONC) only convert *to* JSON: `convert()` returns an
|
||||
* error and the UI disables them in the JSON → direction.
|
||||
*/
|
||||
inputOnly?: boolean;
|
||||
}
|
||||
|
||||
export interface ConversionInput {
|
||||
@@ -57,7 +63,15 @@ export interface ReverseInput {
|
||||
sourceName?: string;
|
||||
}
|
||||
|
||||
export type ConversionResult = { ok: true; output: string } | { ok: false; error: string };
|
||||
export interface ConversionFailure {
|
||||
ok: false;
|
||||
error: string;
|
||||
/** 1-based position of an input syntax error, when the parser knows it. */
|
||||
line?: number;
|
||||
column?: number;
|
||||
}
|
||||
|
||||
export type ConversionResult = { ok: true; output: string } | ConversionFailure;
|
||||
|
||||
/**
|
||||
* Schema describing a single option field, used by the settings UI
|
||||
|
||||
@@ -162,6 +162,18 @@ describe('useConversionResult — small inputs (main thread)', () => {
|
||||
expect(result.current.inputErrorColumn).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the position of a JSONC error', () => {
|
||||
const { result } = setup({
|
||||
input: '[\n 1, /* two */\n 2 3\n]',
|
||||
format: 'jsonc',
|
||||
direction: 'reverse',
|
||||
options: { indent: '2' },
|
||||
});
|
||||
expect(result.current.inputError).toEqual(expect.any(String));
|
||||
expect(result.current.inputErrorLine).toBe(3);
|
||||
expect(result.current.inputErrorColumn).toBe(5);
|
||||
});
|
||||
|
||||
it('re-converts when the options change', () => {
|
||||
const { result, rerender } = setup({
|
||||
input: '[{"a":1}]',
|
||||
|
||||
@@ -34,6 +34,15 @@ describe('useFileAccept', () => {
|
||||
expect(result.allowedExtensions).toEqual(['yaml', 'yml', 'txt']);
|
||||
});
|
||||
|
||||
it('accepts .jsonc and .json files for JSONC going back', () => {
|
||||
const result = accept('jsonc', 'reverse');
|
||||
expect(result.accept).toEqual({
|
||||
'application/jsonc': ['.jsonc', '.json'],
|
||||
'text/plain': ['.txt'],
|
||||
});
|
||||
expect(result.allowedExtensions).toEqual(['jsonc', 'json', 'txt']);
|
||||
});
|
||||
|
||||
it('keys the dropzone map by the format MIME type', () => {
|
||||
const result = accept('jsonl', 'reverse');
|
||||
expect(result.accept).toEqual({
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON.",
|
||||
"copied": "Copied",
|
||||
"error_position": "Ln {{line}}, Col {{column}}",
|
||||
"jsonc_hint": "This looks like JSONC — JSON with comments or trailing commas.",
|
||||
"jsonc_switch": "Convert JSONC → JSON",
|
||||
"output_aria": "{{format}} output (read-only)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "Ready",
|
||||
"suggested": "Suggested for the detected shape",
|
||||
"not_suggested": "Not suggested for the detected shape",
|
||||
"no_reverse": "Reverse parse not supported for this format"
|
||||
"no_reverse": "Reverse parse not supported for this format",
|
||||
"input_only": "Input only: converts to JSON in the → JSON direction"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "Pretty-print each line",
|
||||
"pretty_desc": "Canonical JSONL is single-line. Enable for human-readable multi-line records."
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "Output layout",
|
||||
"indent_desc": "Comments and trailing commas are removed; values, numbers and key order stay exactly as written.",
|
||||
"indent_2": "2 spaces",
|
||||
"indent_4": "4 spaces",
|
||||
"indent_tab": "Tab",
|
||||
"indent_minify": "Minified"
|
||||
},
|
||||
"csv": {
|
||||
"header": "Include header row",
|
||||
"header_desc": "Emit the first row as column names derived from object keys.",
|
||||
@@ -292,7 +304,7 @@
|
||||
"about": {
|
||||
"title": "About JSONPrism",
|
||||
"lead": "A refracting tool for developers.",
|
||||
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
|
||||
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back, plus JSONC (JSON with comments) into plain JSON. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
|
||||
"p2": "Built with React 19, TypeScript 7, Vite 8, Tailwind CSS v4 and shadcn/ui. The web version is served by Cloudflare Workers; the desktop and Android apps are built with Tauri 2. Source on GitHub.",
|
||||
"version": "Version {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON。",
|
||||
"copied": "コピー済み",
|
||||
"error_position": "{{line}} 行 {{column}} 列",
|
||||
"jsonc_hint": "JSONC(コメントや末尾カンマを含む JSON)のようです。",
|
||||
"jsonc_switch": "JSONC → JSON に変換",
|
||||
"output_aria": "{{format}} の出力(読み取り専用)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "利用可能",
|
||||
"suggested": "検出されたデータ形状に適しています",
|
||||
"not_suggested": "検出されたデータ形状には推奨されません",
|
||||
"no_reverse": "この形式は逆方向のパースに対応していません"
|
||||
"no_reverse": "この形式は逆方向のパースに対応していません",
|
||||
"input_only": "入力専用:→ JSON の方向で JSON に変換します"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "各行を整形して出力",
|
||||
"pretty_desc": "標準の JSONL は 1 行 1 レコードです。人間が読みやすい複数行を希望する場合に有効化。"
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "出力レイアウト",
|
||||
"indent_desc": "コメントと末尾のカンマを取り除きます。値・数値・キーの順序は書かれたとおりに保たれます。",
|
||||
"indent_2": "スペース 2 つ",
|
||||
"indent_4": "スペース 4 つ",
|
||||
"indent_tab": "タブ",
|
||||
"indent_minify": "最小化"
|
||||
},
|
||||
"csv": {
|
||||
"header": "ヘッダー行を含める",
|
||||
"header_desc": "オブジェクトのキーから生成した列名を最初の行に出力します。",
|
||||
@@ -259,7 +271,7 @@
|
||||
"about": {
|
||||
"title": "JSONPrism について",
|
||||
"lead": "開発者のための分光ツール。",
|
||||
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
|
||||
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。JSONC(コメント付き JSON)も通常の JSON に変換できます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
|
||||
"p2": "React 19、TypeScript 7、Vite 8、Tailwind CSS v4、shadcn/ui で構築。Web 版は Cloudflare Workers で配信され、デスクトップ版と Android 版は Tauri 2 で構築されています。ソースは GitHub にあります。",
|
||||
"version": "バージョン {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON.",
|
||||
"copied": "Đã chép",
|
||||
"error_position": "Dòng {{line}}, Cột {{column}}",
|
||||
"jsonc_hint": "Có vẻ đây là JSONC — JSON có comment hoặc dấu phẩy thừa.",
|
||||
"jsonc_switch": "Chuyển JSONC → JSON",
|
||||
"output_aria": "Kết quả {{format}} (chỉ đọc)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "Sẵn sàng",
|
||||
"suggested": "Gợi ý cho shape phát hiện được",
|
||||
"not_suggested": "Không gợi ý cho shape phát hiện được",
|
||||
"no_reverse": "Format này không hỗ trợ parse ngược"
|
||||
"no_reverse": "Format này không hỗ trợ parse ngược",
|
||||
"input_only": "Chỉ làm đầu vào: chuyển sang JSON ở chiều → JSON"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "Pretty-print mỗi dòng",
|
||||
"pretty_desc": "JSONL chuẩn là một dòng một record. Bật cái này nếu muốn dạng dễ đọc nhiều dòng."
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "Bố cục output",
|
||||
"indent_desc": "Comment và dấu phẩy thừa bị bỏ; giá trị, số và thứ tự key giữ nguyên như bạn viết.",
|
||||
"indent_2": "2 dấu cách",
|
||||
"indent_4": "4 dấu cách",
|
||||
"indent_tab": "Tab",
|
||||
"indent_minify": "Thu gọn (minify)"
|
||||
},
|
||||
"csv": {
|
||||
"header": "Bao gồm dòng header",
|
||||
"header_desc": "Phát ra dòng đầu tiên là tên cột lấy từ key của object.",
|
||||
@@ -292,7 +304,7 @@
|
||||
"about": {
|
||||
"title": "Về JSONPrism",
|
||||
"lead": "Một công cụ tán sắc cho developer.",
|
||||
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
|
||||
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó, cùng với JSONC (JSON có comment) thành JSON thuần. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
|
||||
"p2": "Xây dựng với React 19, TypeScript 7, Vite 8, Tailwind CSS v4 và shadcn/ui. Bản web chạy trên Cloudflare Workers; ứng dụng desktop và Android được xây dựng bằng Tauri 2. Mã nguồn trên GitHub.",
|
||||
"version": "Phiên bản {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -33,10 +33,13 @@
|
||||
"title_rest": "JSON。",
|
||||
"copied": "已复制",
|
||||
"error_position": "第 {{line}} 行,第 {{column}} 列",
|
||||
"jsonc_hint": "这看起来是 JSONC——带注释或尾随逗号的 JSON。",
|
||||
"jsonc_switch": "转换 JSONC → JSON",
|
||||
"output_aria": "{{format}} 输出(只读)"
|
||||
},
|
||||
"formats": {
|
||||
"jsonl": "JSONL",
|
||||
"jsonc": "JSONC",
|
||||
"csv": "CSV",
|
||||
"tsv": "TSV",
|
||||
"yaml": "YAML",
|
||||
@@ -53,7 +56,8 @@
|
||||
"ready": "可用",
|
||||
"suggested": "适用于检测到的数据形状",
|
||||
"not_suggested": "不推荐用于检测到的数据形状",
|
||||
"no_reverse": "此格式不支持反向解析"
|
||||
"no_reverse": "此格式不支持反向解析",
|
||||
"input_only": "仅作输入:在 → JSON 方向转换为 JSON"
|
||||
},
|
||||
"direction": {
|
||||
"forward": "JSON →",
|
||||
@@ -66,6 +70,14 @@
|
||||
"pretty": "美化每一行",
|
||||
"pretty_desc": "标准 JSONL 为每条记录一行。如需多行人类可读输出,请启用此项。"
|
||||
},
|
||||
"jsonc": {
|
||||
"indent": "输出布局",
|
||||
"indent_desc": "移除注释和尾随逗号;值、数字和键的顺序保持原样。",
|
||||
"indent_2": "2 个空格",
|
||||
"indent_4": "4 个空格",
|
||||
"indent_tab": "制表符",
|
||||
"indent_minify": "压缩"
|
||||
},
|
||||
"csv": {
|
||||
"header": "包含表头行",
|
||||
"header_desc": "以对象键作为列名输出第一行。",
|
||||
@@ -259,7 +271,7 @@
|
||||
"about": {
|
||||
"title": "关于 JSONPrism",
|
||||
"lead": "为开发者打造的分光工具。",
|
||||
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
|
||||
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON,JSONC(带注释的 JSON)也能转为标准 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
|
||||
"p2": "基于 React 19、TypeScript 7、Vite 8、Tailwind CSS v4 和 shadcn/ui 构建。网页版由 Cloudflare Workers 提供服务;桌面版和 Android 版使用 Tauri 2 构建。源代码托管在 GitHub。",
|
||||
"version": "版本 {{version}}",
|
||||
"donate": {
|
||||
|
||||
@@ -62,6 +62,16 @@ describe('runConversion', () => {
|
||||
).toBe('input-error');
|
||||
});
|
||||
|
||||
it('passes a reverse error position through when the parser knows it', () => {
|
||||
const { outcome } = runConversion({
|
||||
text: '// config\n{"a": 1 "b": 2}',
|
||||
format: 'jsonc',
|
||||
direction: 'reverse',
|
||||
options: { indent: '2' },
|
||||
});
|
||||
expect(outcome).toMatchObject({ kind: 'input-error', line: 2, column: 9 });
|
||||
});
|
||||
|
||||
it('flags precision loss on huge integers', () => {
|
||||
const { outcome } = runConversion({
|
||||
text: '{"id": 12345678901234567890}',
|
||||
|
||||
@@ -6,6 +6,7 @@ import { editorLanguageFor, outputLanguageFor } from '../editor-language';
|
||||
/** Expected CodeMirror language for text written in each format. */
|
||||
const FORMAT_LANGUAGE: Record<FormatId, string> = {
|
||||
jsonl: 'jsonl',
|
||||
jsonc: 'jsonc',
|
||||
csv: 'plain',
|
||||
tsv: 'plain',
|
||||
yaml: 'yaml',
|
||||
|
||||
+15
-9
@@ -71,15 +71,21 @@ function convertOnce({
|
||||
if (direction === 'reverse') {
|
||||
if (typeof converter.reverse !== 'function') return { kind: 'no-reverse' };
|
||||
const result = safeReverse(converter, { text, ...(sourceName ? { sourceName } : {}) }, options);
|
||||
return result.ok
|
||||
? {
|
||||
kind: 'ok',
|
||||
output: result.output,
|
||||
shape: null,
|
||||
precisionLoss: false,
|
||||
outputBytes: utf8ByteLength(result.output),
|
||||
}
|
||||
: { kind: 'input-error', message: result.error };
|
||||
if (!result.ok) {
|
||||
return {
|
||||
kind: 'input-error',
|
||||
message: result.error,
|
||||
...(result.line !== undefined ? { line: result.line } : {}),
|
||||
...(result.column !== undefined ? { column: result.column } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: 'ok',
|
||||
output: result.output,
|
||||
shape: null,
|
||||
precisionLoss: false,
|
||||
outputBytes: utf8ByteLength(result.output),
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseCached(text);
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ export function errorPosition(
|
||||
return offsetToLineColumn(text, offset);
|
||||
}
|
||||
|
||||
function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
|
||||
export function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
|
||||
let line = 1;
|
||||
let column = 1;
|
||||
const end = Math.min(offset, text.length);
|
||||
|
||||
@@ -11,6 +11,8 @@ function languageOfFormat(format: FormatId): EditorLanguage {
|
||||
return 'xml';
|
||||
case 'jsonl':
|
||||
return 'jsonl';
|
||||
case 'jsonc':
|
||||
return 'jsonc';
|
||||
case 'markdown':
|
||||
return 'markdown';
|
||||
case 'sql':
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useWorkspaceStore } from '../workspaceStore';
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -51,3 +51,26 @@ describe('workspaceStore', () => {
|
||||
expect(useWorkspaceStore.getState().optionsByFormat['jsonl']).toEqual({ pretty: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('workspaceStore initial state', () => {
|
||||
/** The store reads storage once, at module load — import a fresh copy per scenario. */
|
||||
async function loadStore() {
|
||||
vi.resetModules();
|
||||
const { useWorkspaceStore: store } = await import('../workspaceStore');
|
||||
return store;
|
||||
}
|
||||
|
||||
it('restores the stored format and direction', async () => {
|
||||
window.localStorage.setItem('jsonprism.selected_format', 'yaml');
|
||||
window.localStorage.setItem('jsonprism.direction', 'reverse');
|
||||
const store = await loadStore();
|
||||
expect(store.getState()).toMatchObject({ format: 'yaml', direction: 'reverse' });
|
||||
});
|
||||
|
||||
it('opens an input-only format in the → JSON direction', async () => {
|
||||
window.localStorage.setItem('jsonprism.selected_format', 'jsonc');
|
||||
window.localStorage.setItem('jsonprism.direction', 'forward');
|
||||
const store = await loadStore();
|
||||
expect(store.getState()).toMatchObject({ format: 'jsonc', direction: 'reverse' });
|
||||
});
|
||||
});
|
||||
@@ -45,13 +45,15 @@ function readInitialFormat(): FormatId {
|
||||
return isFormatId(stored) ? stored : DEFAULT_FORMAT;
|
||||
}
|
||||
|
||||
function readInitialDirection(): Direction {
|
||||
function readInitialDirection(format: FormatId): Direction {
|
||||
// An input-only format (JSONC) has no JSON → direction.
|
||||
if (getConverter(format).meta.inputOnly) return 'reverse';
|
||||
return safeGetItem(STORAGE_DIRECTION_KEY) === 'reverse' ? 'reverse' : 'forward';
|
||||
}
|
||||
|
||||
export const useWorkspaceStore = create<WorkspaceState>((set, get) => {
|
||||
const initialFormat = readInitialFormat();
|
||||
const initialDirection = readInitialDirection();
|
||||
const initialDirection = readInitialDirection(initialFormat);
|
||||
const initialOptions: Record<string, Record<string, unknown>> = {
|
||||
[initialFormat]: loadOptions(initialFormat, getConverter(initialFormat)),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user